我使用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()函数之外,但没有帮助.

推荐答案

global line_plotted

——>

nonlocal line_plotted

移动函数内的所有代码后,line_plotted不存在于全局级别,非本地关键字用于引用最近作用域中的变量.

Edit: full code

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()

Python相关问答推荐

通过在测验程序中添加解释来加强学习

将数组操作转化为纯numpy方法

螺旋桨图上意外颠倒的次y轴

Pandas滚动分钟,来自其他列的相应值

Ibis中是否有一个ANY或ANY_UTE表达,可以让我比较子查询返回的一组值中的值?

如何在不使用字符串的情况下将namedtuple属性传递给方法?

sys.modulesgo 哪儿了?

当值是一个integer时,在Python中使用JMESPath来验证字典中的值(例如:1)

symy.分段使用numpy数组

如何使用entry.bind(FocusIn,self.Method_calling)用于使用网格/列表创建的收件箱

Python中使用时区感知日期时间对象进行时间算术的Incredit

Pandas 填充条件是另一列

删除任何仅包含字符(或不包含其他数字值的邮政编码)的观察

如何使用它?

使用NeuralProphet绘制置信区间时出错

调用decorator返回原始函数的输出

不能使用Gekko方程'

如何在Python中使用另一个数据框更改列值(列表)

如果初始groupby找不到满足掩码条件的第一行,我如何更改groupby列,以找到它?

Python—转换日期:价目表到新行