首页 > 解决方案 > 如何从 Dataframe 图中切换线的可见性?

问题描述

我有一个熊猫数据框,其中包含大约 8 行需要绘制。我想清楚地看到这些线条,因为有这么多线条拦截会变得混乱。我看到了一个使用图例选择来切换线的可见性的解决方案,但这需要将图例线与图中的实际线相匹配。

有没有办法让这些线或任何其他方式来切换其可见性?

至于我的代码,在准备好数据框之后,我只是在绘制:

df.plot(figsize=(20, 8), fontsize=16)
plt.show()

标签: pythonpandasdataframematplotlib

解决方案


df.plot()返回一个axes.Axes对象,它有一个.get_lines()方法。正如锡上所说,这会返回绘制的线。

这是您引用的示例,围绕 a 重写pd.DataFrame.plot

ax = df.plot(figsize=(20, 8), fontsize=16)
ax.set_title('Click on legend line to toggle line on/off')
leg = ax.legend(fancybox=True, shadow=True)

lined = {}  # Will map legend lines to original lines.
for legline, origline in zip(leg.get_lines(), ax.get_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)
    ax.get_figure().canvas.draw()

ax.get_figure().canvas.mpl_connect('pick_event', on_pick)
plt.show()

然而,我发现图例中线条的点击框相当小,所以也许你需要点击一下以找出它在哪里(我必须瞄准图例线条的上边缘)。


推荐阅读