Matplotlib 悬停文本

Matplotlib Hover Text

我使用 Matplotlib 和 Squarify 创建了这个 tree map。有没有办法在鼠标悬停在轴上时显示每个轴的信息?

mplcursors 库可用于在悬停时创建自定义注释。这是一个带有树图的示例:

import matplotlib.pyplot as plt
import matplotlib as mpl
import squarify
import mplcursors

sizes = [5, 20, 30, 25, 10, 12]
sumsizes = sum(sizes)
labels = ['A', 'B', 'C', 'D', 'E', 'F']

cmap = plt.cm.get_cmap('Greens')
norm = plt.Normalize(vmin=min(sizes), vmax=max(sizes))
colors = [cmap(norm(s)) for s in sizes]
squarify.plot(sizes=sizes, label=labels, color=colors)
plt.colorbar(plt.cm.ScalarMappable(cmap=cmap, norm=norm))

cursor = mplcursors.cursor(hover=True)
cursor.connect("add", lambda sel: sel.annotation.set_text(
    f"ID:{sel.target.index} '{labels[sel.target.index]}'\nSize:{sizes[sel.target.index]} ({sizes[sel.target.index] * 100.0 / sumsizes:.1f} %)"))

plt.show()