我使用matplotlib与Python制作了一个交互式情节,我想通过将其放入函数中来调用它. 一切都正常工作,直到我将整个代码放入get_plot()函数中.在不使用make_plot()函数的情况下运行代码,可以得到我想要的结果.为什么在另一个功能中时它不再工作(我只是失go 了交互功能)?
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import numpy as np
def make_plot():
def button_clicked(event):
global line_plotted
if line_plotted:
ax1.lines[1].remove()
line_plotted = False
else:
ax1.plot(line[0], line[1], color='r', linestyle='--')
line_plotted = True
fig.canvas.draw()
plt.ion()
x = np.linspace(0, 4*np.pi, 500)
y = np.sin(x)
line = [0, 4 * np.pi], [1, 1]
fig = plt.figure(figsize=(15,5))
ax1 = fig.add_subplot()
ax1.plot(x,y)
ax1.plot(line[0], line[1], color='r', linestyle='--')
line_plotted = True
button_ax = plt.axes([0.8, 0.05, 0.1, 0.075])
button = Button(button_ax, 'Show red line')
button.on_clicked(button_clicked)
plt.show()
make_plot()
我try 将button_clicked(事件)函数放在make_plot()函数之外,但没有帮助.