我使用 matplotlib 用 python 制作了一个交互式绘图,我想通过将其放入函数中来调用它。 一切正常,直到我将整个代码放入函数 make_plot() 中。在没有 make_plot() 函数的情况下运行代码给了我我想要的东西。为什么它在另一个函数中不再工作(我只是失去了交互功能)?
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()
我尝试将button_clicked(event)函数放在make_plot()函数之外,但没有帮助。
global line_plotted
-->
nonlocal line_plotted
将所有代码移动到函数内后,line_plotted 不再存在于全局级别,非局部关键字用于引用最近范围内的变量。
编辑:完整代码
在pycharm和spyder中运行都是交互式的——点击按钮。
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import numpy as np
matplotlib.use("TkAgg")
def make_plot():
def button_clicked(event):
nonlocal 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(block=True)
make_plot()