如何使用拾取图例(matplotlib)自动缩放图形?

How to autoscaled graphs with picking legend (matplotlib)?

我正在使用 matplotlib 编写采摘图例。目标是通过单击图例来隐藏和显示曲线。我找到了这个解决方案 (),效果很好。

我想改进此代码以在每次点击图例后自动调整轴。我不知道这是否可能。你有什么提示吗?

他们是我想要的下图示例。首先,图像 1 代表图形。然后在点击图例 5*sin(x) 后,橙色曲线按预期消失(图 2)。在图像 2 上,y 轴未优化。预期的结果在图 3 上。

Example

非常感谢,

在 visible_only 标志设置为 True 的情况下添加对 relim 方法的调用并更新轴应该按照您想要的方式执行。这需要添加到您的 on_click/update 方法中。

# Where ax2 is a reference to your second axis
ax2.relim(visible_only=True)  # Ignore the line you've hidden when rescaling.
ax2.autoscale_view()  # assuming the axis has not been altered by set_xlim etc.