matplotlib 功能动画:运行时间错误:动画函数必须返回Artist对象序列

esyap4oy  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(221)

我正在尝试使用Python中matplotlib的动画模块绘制实时温度数据。我通过USB连接从海岸224温度监测器获取温度数据
下面是我调整后的代码(来源:https://learn.sparkfun.com/tutorials/graph-sensor-data-with-python-and-matplotlib/update-a-graph-in-real-time):

import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from lakeshore import Model224

# You can ignore the following try and except block, it's a workaround for a different small problem
try:
    from IPython import get_ipython
    get_ipython().magic('clear')
    get_ipython().magic('reset -f')
except:
    pass

# Create figure for plotting

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xs = []
ys = []

myinstrument = Model224()

# This function is called periodically from FuncAnimation
def animate(i, xs, ys):
    # Read temperature from port A
    temperature_A = myinstrument.get_kelvin_reading('A')
    
    # Add x and y to lists
    xs.append(dt.datetime.now().strftime('%H:%M:%S.%f'))
    ys.append(temperature_A)
    
    # Limit x and y lists to 20 items
    xs = xs[-20:]
    ys = ys[-20:]
    
    # Draw x and y lists
    ax.clear()
    ax.plot(xs, ys)
    
    # Format plot
    plt.xticks(rotation=45, ha='right')
    plt.subplots_adjust(bottom=0.30)
    plt.ylabel('Temperature [K]')

# Set up plot to call animate() function periodically

ani = animation.FuncAnimation(fig = fig, func =  animate, fargs=(xs,ys), interval=10000, blit = True)
plt.show()

字符串
但是,我得到了以下错误消息:

RuntimeError: The animation function must return a sequence of Artist objects.


一开始,我确实按照本例中的here进行了设置:

blit = False


我没有看到任何错误信息,只是一个空白的白色图。有趣的是,它从未进入animate-Function。
之后,我调整了代码并添加了:

blit = True


对于函数输入,我至少得到了以下情节:
x1c 0d1x的数据
我得到上面描述的RuntimeError。
尽管如此,我还是期待着一个实时的温度图,就像在原来的来源。

hwazgwia

hwazgwia1#

当使用blitting,as per the documentation时,您需要返回更改的艺术家。使用FuncAnimation的一般方法是创建一个空白图并保存它返回的Line2D对象。在每个循环中,您可以使用line.set_data()更新该行的数据,然后返回该行进行位传输。当正确使用FuncAnimation时,您不需要担心清除图形。
由于我没有传感器,我只是在开始时产生一些数据,并在下面的示例中慢慢绘制。

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

plt.close("all")

rng = np.random.default_rng(42)
N = 1000
xdata = np.linspace(0, 10, N)
ydata = np.sin(5*xdata)

fig, ax = plt.subplots()
line, = ax.plot([], [])
plt.xticks(rotation=45, ha="right")
ax.set_ylabel("Temperature [K]")
ax.set_ylim(-1.5, 1.5)

xs = []
ys = []

def animate(i, xs, ys):    
    xs.append(xdata[i])
    ys.append(ydata[i])
    
    xs = xs[-20:]
    ys = ys[-20:]
    
    line.set_data(xs, ys)
    ax.set_xlim(min(xs), max(xs))
    
    return line,

ani = animation.FuncAnimation(fig, animate, frames=N, fargs=(xs, ys), interval=10, blit=True)
fig.show()

字符串

相关问题