【问题标题】:How to toggle line's visibility from Dataframe plot?如何从 Dataframe 图中切换线的可见性?
【发布时间】:2021-08-17 15:54:46
【问题描述】:

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

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

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

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

【问题讨论】:

  • 您可能需要向我们提供这些数据
  • 您可能需要考虑为此使用 plotly express。 Plotly 线图自动提供这种交互性。

标签: python pandas dataframe matplotlib


【解决方案1】:

您的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()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多