python - 如何从 Dataframe 图中切换线的可见性?
问题描述
我有一个熊猫数据框,其中包含大约 8 行需要绘制。我想清楚地看到这些线条,因为有这么多线条拦截会变得混乱。我看到了一个使用图例选择来切换线的可见性的解决方案,但这需要将图例线与图中的实际线相匹配。
有没有办法让这些线或任何其他方式来切换其可见性?
至于我的代码,在准备好数据框之后,我只是在绘制:
df.plot(figsize=(20, 8), fontsize=16)
plt.show()
解决方案
你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()
然而,我发现图例中线条的点击框相当小,所以也许你需要点击一下以找出它在哪里(我必须瞄准图例线条的上边缘)。
推荐阅读
- authentication - Auth0 - 不同组织的移动应用程序
- docker - Filebeat 停止向 Logstash 发送数据,因此 Elasticsearch 在几十万个文档后停止发送数据,重新启动 Filebeat 容器
- python - 使用字典计数并删除不相关的值
- metadata - Shibboleth SP 配置异常 shibboleth 处理程序在未配置的位置调用 (http://Shub.adatum.com/Shibboleth.sso/login)
- javascript - 如何使用 jQuery 选择仅包含空格的元素?
- javascript - 如果键具有特定元素,则不显示组件
- python - pypfopt (PyPortfolioOpt) 库 从每周回报计算年化预期回报
- kubernetes - 通过秘密文件在 Kubernetes 中使用变量
- reactjs - reactjs下拉父菜单路由不起作用
- php - 用于在 php 中提取 db 数据的嵌套 while 循环