【问题标题】:matplotlib legend picking with pandas dataframe doesn't work使用 pandas 数据框挑选 matplotlib 图例不起作用
【发布时间】:2021-03-01 14:01:56
【问题描述】:

我有以下数据框:

>>>  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 来获取每一行。不知道如何处理。

【问题讨论】:

    标签: python pandas matplotlib interactive line-plot


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2014-04-11
      • 2012-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 2020-01-19
      相关资源
      最近更新 更多