python - Matplotlib 悬停文本
问题描述
我使用 Matplotlib 和 Squarify创建了这个树形图。当鼠标悬停在轴上时,有没有办法显示有关每个轴的信息?
解决方案
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()
推荐阅读
- debugging - 使用 Juno IDE 调试 Julia 脚本
- pandas - 选择具有组最小值的所有数据框行
- oracle - 如何修复 java.sql.SQLDataException: ORA-01847: day of month must be between 1 and last day of month 错误?
- google-apps-script - 使用 Google Apps 脚本从 Google 表格数据表复制到 Google 文档表
- r - 翻译Stata循环
- php - 如何将通过“For循环”的所有数字放在PHP中的一个数组中
- linkedin-api - 如何将 w_fullprofile 范围添加到 Linkedin 应用程序
- dialogflow-es - 如何在对话流 PHP 中创建意图时设置输出上下文?
- phpmyadmin - phpmyadmin 使用什么默认端口?
- c# - HttpPostedFile 返回空值?