使用Pandas数据框拾取matplotlib图例无效

2024-06-16 09:06:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

>>>  60.1   65.5    67.3    74.2    88.5 ... 
A1   0.45   0.12    0.66    0.76    0.22
B4   0.22   0.24    0.12    0.56    0.34
B7   0.12   0.47    0.93    0.65    0.21
...

我正在尝试创建线条图,并能够启用/禁用某些线条(如显示或隐藏图例中的某些项目)。我找到了this。这里的示例使用numpy,而不是pandas dataframe。当我尝试将其应用于我的应用程序时,我会设法创建绘图,但不是交互式的:

%matplotlib notebook
def on_pick(event):
    # On the pick event, find the original line corresponding to the legend
    # proxy line, and toggle its visibility.
    legline = event.artist
    origline = lined[legline]
    visible = not origline.get_visible()
    origline.set_visible(visible)
    # Change the alpha on the line in the legend so we can see what lines
    # have been toggled.
    legline.set_alpha(1.0 if visible else 0.2)
    fig.canvas.draw()
test.T.plot()
fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()

enter image description here

我得到绘图,但无法单击图例项并显示或隐藏它们。

我的最终目标是:能够使用matplotlib中的on_pick函数以交互方式显示或隐藏图例中的线条

编辑:我理解我对文档的这一部分有问题:


lines = [line1, line2]
lined = {}  # Will map legend lines to original lines.
for legline, origline in zip(leg.get_lines(), lines):
    legline.set_picker(True)  # Enable picking on the legend line.
    lined[legline] = origline

正如我看到的,这里的行是“一个接一个”的,但在我的脚本中,我使用pandas和T来获得每一行。不知道该怎么处理


Tags: theeventpandasonline线条lines图例
1条回答
网友
1楼 · 发布于 2024-06-16 09:06:40

首先,您需要提取图形上的所有line2D对象。您可以使用ax.get_lines()获取它们。下面是一个例子:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))
ts = ts.cumsum()
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list("ABCD"))
df = df.cumsum()
fig, ax = plt.subplots()
df.plot(ax=ax)
lines = ax.get_lines()
leg = ax.legend(fancybox=True, shadow=True)
lined = {}  # Will map legend lines to original lines.
for legline, origline in zip(leg.get_lines(), lines):
    legline.set_picker(True)  # Enable picking on the legend line.
    lined[legline] = origline

def on_pick(event):
    #On the pick event, find the original line corresponding to the legend
    #proxy line, and toggle its visibility.
    legline = event.artist
    origline = lined[legline]
    visible = not origline.get_visible()
    origline.set_visible(visible)
    #Change the alpha on the line in the legend so we can see what lines
    #have been toggled.
    legline.set_alpha(1.0 if visible else 0.2)
    fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()

相关问题 更多 >