使用 pandas 数据框的 matplotlib 图例选择不起作用

matplotlib legend picking with pandas dataframe doesn't work

我有以下数据框:

>>>  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 数据框。当我尝试在我的 pandas df 上应用它时,我设法创建了绘图但不是交互式的:

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

我得到了情节,但无法点击图例项目并显示或隐藏它们。

我的最终目标:能够使用 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 来“逐行”获取每一行。不知道该如何处理。

首先,您需要提取图形上的所有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()