如何从数据帧图中切换线的可见性?



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

是否有办法获得这些线条或其他方式来切换其可见性?

对于我的代码,在准备好数据框架之后,我只是绘制:
df.plot(figsize=(20, 8), fontsize=16)
plt.show()

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

这是您引用的围绕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()

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

最新更新