(Python) 如何向 Pandas 图中添加工具提示? [英] (Python) How to add tooltips to Pandas plots?

查看:66
本文介绍了(Python) 如何向 Pandas 图中添加工具提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何绘制 Pandas 线图,其中有工具提示指示线的标签和鼠标所在点的值?

How does one plot Pandas line plots where there are tooltips indicating both the label of the line and the value of the point the mouse is over?

熊猫图可能有十多条不同的线,带有不同的图例标签.工具提示应该输出(标签,值).如果这个要求太多,那么标签就可以了.

A pandas plot may have a dozen different lines with different legend labels. The tooltip should output (label, value). If this is too much to ask, then just the label is fine.

我更喜欢 mpld3,但任何其他绘图包都可以.在 mpld3 中,您是否使用 PointLabelTooltip 或 LineLabelTooltip 来处理熊猫图?请提供示例代码.

I have a preference for mpld3 but any other plotting package is ok. In mpld3, do you use PointLabelTooltip or LineLabelTooltip to work for pandas plots? Please provide an example code.

以下代码给出错误,因为 PointLabelTooltip 需要的是点,而不是线:

The following code gives an error, because the PointLabelTooltip is expecting points, not lines:

import mpld3
mpld3.enable_notebook()
fig, ax = plt.subplots()
df = pd.DataFrame(np.cumsum(np.random.normal(0,1,(12,1000)),axis=1).T)
axes = df.plot(figsize=(14,4), colormap='spectral');

labels = list(df.columns.values)
tooltip = mpld3.plugins.PointLabelTooltip(axes.get_lines()[0],labels=labels)
mpld3.plugins.connect(fig, tooltip) 

<小时>

Javascript error adding output!
TypeError: null is not an object (evaluating 'obj.elements')
See your browser Javascript console for more details.

推荐答案

要将简单的工具提示放在一行,您可以使用 mpld3.plugin.LineLabelTooltip.你必须为每一行做一次.这是您的代码的修改版本:

To put a simple tooltip on a line, you can use mpld3.plugin.LineLabelTooltip. You must do it once for each line. Here is a modified version of your code:

import mpld3, pandas as pd
mpld3.enable_notebook()

df = pd.DataFrame(np.cumsum(np.random.normal(0,1,(5,1000)),axis=1).T)
axes = df.plot(figsize=(14,4), colormap='spectral');

labels = list(df.columns.values)
for i in range(len(labels)):
    tooltip = mpld3.plugins.LineLabelTooltip(axes.get_lines()[i], labels[i])
    mpld3.plugins.connect(plt.gcf(), tooltip) 

这篇关于(Python) 如何向 Pandas 图中添加工具提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆