使用matplotlib绘制实时图形

jchrr9hc  于 2023-02-09  发布在  其他
关注(0)|答案(1)|浏览(238)

我正在尝试一个代码来绘制一个实时图,但我总是得到一个空图。下面是我的代码:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import random

style.use('fivethirtyeight')

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

def animate(i):
    y = random.randint(0,100) # generate random data
    x = i # set x as iteration number
    ax1.clear()
    ax1.plot(x, y, 'ro')

ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()

我收到警告,但我正在使用plt.show()显示动画。不确定我做错了什么:

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 have outputted the Animation using `plt.show()` or `anim.save()`.
  warnings.warn(

46scxncf

46scxncf1#

问题似乎出在Spyder使用的绘图后端。默认情况下,Spyder使用的后端不支持动画。
您可以尝试在终端中运行独立脚本中的代码,而不是在Spyder中运行。您也可以尝试使用其他绘图后端,如Qt5Agg或TkAgg。您可以使用以下代码行更改后端:

import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import random

style.use('fivethirtyeight')

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.set_xlim(0,100)
ax1.set_ylim(0,100)

x_vals = []
y_vals = []

def animate(i):
    y = random.randint(0,100) # generate random data
    x = i # set x as iteration number
    x_vals.append(x)
    y_vals.append(y)
    ax1.clear()
    ax1.plot(x_vals, y_vals, 'ro')

ani = animation.FuncAnimation(fig, animate, frames=100, interval=1000)
plt.show()

这应该可以解决问题,并在绘图窗口中显示实时图形。

相关问题