使用一个按钮来显示和关闭Matplotlib实时图

brjng4g3  于 2023-04-07  发布在  其他
关注(0)|答案(1)|浏览(177)

我正在构建一个程序,其中我有一个实时图形使用使用matplotlib。我使用tkinter制作2个按钮:“graph it”打开一个新窗口来绘制图,“clear”关闭窗口。问题是,当我第一次用“clear”按钮关闭窗口时,我不能用“graph it”按钮重新显示图形。相反,它给了我这个错误:

"UserWarning: Animation was deleted without rendering anything. This is most likely 
not intended. To prevent deletion, assign the Animation to a variable, e.g. `anim`, that exists until you output the Animation using `plt.show()` or `anim.save()`.

下面是我的代码:

import datetime as dt
import random
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from tkinter import *
#import tmp102

# Create figure for plotting
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xs = []
ys2 = []
ys = []

# Initialize communication with TMP102
#tmp102.init()

# This function is called periodically from FuncAnimation
def animate(i,xs, ys, ys2):

    # Read temperature (Celsius) from TMP102
    #temp_c = round(tmp102.read_temp(), 2)

    num_random = random.randint(0,100)
    num_random2 = random.randint(0,100)
    # Add x and y to lists
    xs.append(dt.datetime.now().strftime('%H:%M:%S.%f'))
    ys.append(num_random)
    ys2.append(num_random2)

    # Limit x and y lists to 20 items
    xs = xs[-15:]
    ys = ys[-15:]
    ys2 = ys2[-15:]

    # Draw x and y lists
    ax.clear()
    ax.plot(xs, ys, ys2)

    # Format plot
    plt.xticks(rotation=45, ha='right')
    plt.subplots_adjust(bottom=0.30)
    plt.title('TMP102 Temperature over Time')
    plt.ylabel('Temperature (deg C)')

# Set up plot to call animate() function periodically
def graph():
    ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys, ys2), interval=1000)
    plt.show()

def clear():
    plt.close()

root = Tk()
root.title('matplot with tkinter test')
root.geometry("400x200")

my_button = Button(root, text="Graph it", command=graph)
my_button.pack()

clear_button = Button(root, text="Clear", command=clear)
clear_button.pack()
root.mainloop()

我希望按钮能够显示和关闭的实时图形的任何时候按下按钮

vsaztqbk

vsaztqbk1#

运行plt.close()时,实际上是删除了之前创建的图形fig,因此必须重新创建该图形。

# Create figure for plotting
def create_figure():  # <-- turned into a method
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    xs = []
    ys2 = []
    ys = []
    return fig, ax, xs, ys2, ys

def animate(i,xs, ys, ys2, ax):  # <-- added ax as an argument
    # body omitted

def graph():
    fig, ax, xs, ys2, ys = create_figure()  # <-- recreate the figure object
    ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys, ys2, ax), interval=1000)
    plt.show()

def clear():
    plt.close()

root = Tk()
...

或者,你可以使用plt.close()以外的其他命令,这样你就不会删除你的图形。你可以使用plt.clf()来清除它,而不是同时删除窗口。

相关问题