python-2.7 - 使用MPLD3制作交互式条形图

标签 python-2.7 matplotlib mpld3

我正在尝试制作交互式条形图,但不知道如何标记框。给定一个直方图,我希望拥有它,以便当光标位于条形上方时,显示高度或我想要的任何标签。以下代码显示图表但不带标签:

hist, bins = np.histogram(df.PER, bins=15)
width = 1 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2

fig, ax = plt.subplots()
boxes = ax.bar(center, hist, align='center', width=width,alpha=0.7,facecolor="red",edgecolor='w')

tooltip = mpld3.plugins.PointHTMLTooltip(boxes[0],labels=bins.tolist(),
                                   voffset=10, hoffset=10)
mpld3.plugins.connect(fig, tooltip)

mpld3.display()

其中 df.PER 是来自此处的数据:

0      35.47
1      31.27
2      30.64
3      26.92
4      26.71
5      26.49
6      26.45
7      26.21
8      26.17
9      25.85
10     25.48
11     25.34
12     24.64
13     24.32
14     23.46
15     23.42
16     23.37
17     22.76
18     22.45
19     22.45
20     22.43
21     22.10
22     21.99
23     21.82
24     21.62
25     21.44
26     21.31
27     21.26
28     21.26
29     20.87

有什么建议吗?

最佳答案

对我来说,您的代码为条形图中的第一个条形创建了一个工具提示标签。您可以使用循环来获取其余部分:

for i, box in enumerate(boxes.get_children()):
    tooltip = mpld3.plugins.LineLabelTooltip(box, label=bins[i])
    mpld3.plugins.connect(fig, tooltip)

这里是a notebook showing the results in context .

此功能has been requested previously, and would be nice to offer more directly ,例如如mpld3.plugins.BarTooltip ;欢迎补丁!

关于python-2.7 - 使用MPLD3制作交互式条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34474491/

相关文章:

python - 使用 Matplotlib 和 mpld3 在 Web 浏览器上生成多个图形

python-2.7 - 使用 systemd 运行时 pygame.init() 失败

python-2.7 - 如何使用 Python 以运行顺序重命名 JPG 文件

Python -- matplotlib 椭圆曲线

python - Matplotlib:如何让条形图填满整个 x 轴?

python - 使用 python 和 networkx 的节点上的交互式标签

python - 获取数据框每行的第 n 个排名列 ID - Python/Pandas

python - 绘制垂直条而不是点,plot_date

python - MatPlotLib——对象的大小