我有一个关于使用
autoscale_view()
的请求。我原以为它会只考虑可见艺术家来缩放情节,但它没有这样的效果。
我有一个小测试脚本如下,欢迎任何帮助:
import matplotlib.pyplot as plt
import numpy as np
x1 = np.linspace(0, 10, 100)
y1 = np.sin(x1)
x2 = np.linspace(5, 15, 100)
y2 = np.cos(x2)
fig, ax = plt.subplots()
ax.set_title('Click on legend line to toggle line on/off')
(line1, ) = ax.plot(x1, y1, lw=2, label='1 Hz')
(line2, ) = ax.plot(x2, y2, lw=2, label='2 Hz')
leg = ax.legend()
lines = [line1, line2]
map_legend_to_ax = {} # Will map legend lines to original lines.
pickradius = 5
for legend_line, ax_line in zip(leg.get_lines(), lines):
legend_line.set_picker(pickradius)
map_legend_to_ax[legend_line] = ax_line
def on_pick(event):
legend_line = event.artist
ax_line = map_legend_to_ax[legend_line]
visible = not ax_line.get_visible()
ax_line.set_visible(visible)
legend_line.set_alpha(1.0 if visible else 0.2)
ax.relim()
ax.autoscale_view()
fig.canvas.draw()
fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()
relim()
方法不会忽略不可见曲线,因此应明确设置轴限制。
## the first part of your code
def on_pick(event):
legend_line = event.artist
ax_line = map_legend_to_ax[legend_line]
visible = not ax_line.get_visible()
ax_line.set_visible(visible)
legend_line.set_alpha(1.0 if visible else 0.2)
# update the axes limits considering only visible curves
ax_lines = [line for line in lines if line.get_visible()]
if ax_lines:
ax.set_xlim(
min(line.get_xdata().min() for line in ax_lines),
max(line.get_xdata().max() for line in ax_lines)
)
ax.set_ylim(
min(line.get_ydata().min() for line in ax_lines),
max(line.get_ydata().max() for line in ax_lines)
)
else:
ax.set_xlim(0, 1) # Reset to default if no curves are visible
ax.set_ylim(0, 1)
fig.canvas.draw()
fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()