首页 > 解决方案 > Matplotlib 悬停文本

问题描述

我使用 Matplotlib 和 Squarify创建了这个树形图。当鼠标悬停在轴上时,有没有办法显示有关每个轴的信息?

标签: pythonmatplotlibdata-visualizationmplcursorssquarify

解决方案


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()

结果图


推荐阅读