import matplotlib.pyplot as plt
from matplotlib.widgets import Button
# 创建一个示例图形
fig, ax = plt.subplots()
line, = ax.plot([1, 2, 3], label='Line 1')
# 添加图例
legend = ax.legend(loc='upper right', draggable=True)
# 添加一个按钮,用于切换图例的可见性
ax_button = plt.axes([0.81, 0.02, 0.1, 0.04])
button = Button(ax_button, 'Toggle Legend')
def toggle_legend(event):
legend.set_visible(not legend.get_visible())
plt.draw()
button.on_clicked(toggle_legend)
plt.show()