gpt4 book ai didi

python - Matplotlib 动画不在类内更新

转载 作者:行者123 更新时间:2023-12-01 09:07:31 24 4
gpt4 key购买 nike

我正在编写一个简单的类来实时绘制传感器值;但是,动画不在类内运行。

我尝试返回动画对象以在类之外拥有一个实例,但这不起作用。

据我了解,这与 GitHub #1656 中提出的问题相同。

import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from random import random


class Animate:

def __init__(self, sensor):
# Create figure for plotting
self.fig = plt.figure()
self.ax = self.fig.add_subplot(1, 1, 1)
self.xs = []
self.ys = []
self.ylabel = sensor
self.readings = 20

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

# Get sensor value
value = random()

# Add x and y to lists
self.xs.append(dt.datetime.now().strftime('%H:%M:%S.%f'))
self.ys.append(value)

# Limit x and y lists to 20 items
self.xs = self.xs[-self.readings:]
self.ys = self.ys[-self.readings:]

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

# Format plot
plt.xticks(rotation=45, ha='right')
plt.subplots_adjust(bottom=0.30)
plt.title(self.ylabel + ' over Time')
plt.ylabel(self.ylabel)

def start(self):
print('Starting')
# Set up plot to call animate() function periodically
self.anim = animation.FuncAnimation(self.fig, self._update, fargs=(self.xs, self.ys), interval=200)
plt.show();


rand = Animate('Torque')
rand.start();

最佳答案

您的变量xsys已命名为self.xsself.ys,可以访问在类命名空间中;您不需要将它们传递给 self.update

import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from random import random


class Animate:

def __init__(self, sensor):
# Create figure for plotting
self.fig = plt.figure()
self.ax = self.fig.add_subplot(1, 1, 1)
self.xs = []
self.ys = []
self.ylabel = sensor
self.readings = 20

# This function is called periodically from FuncAnimation
def _update(self, i):

# Read temperature (Celsius) from TMP102
temp_c = random()

# Add x and y to lists
self.xs.append(dt.datetime.now().strftime('%H:%M:%S.%f'))
self.ys.append(temp_c)

# Limit x and y lists to 20 items
self.xs = self.xs[-self.readings:]
self.ys = self.ys[-self.readings:]

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

# Format plot
plt.xticks(rotation=45, ha='right')
plt.subplots_adjust(bottom=0.30)
plt.title(self.ylabel + ' over Time')
plt.ylabel(self.ylabel)

def start(self):
print('Starting')
# Set up plot to call animate() function periodically
self.anim = animation.FuncAnimation(self.fig, self._update, interval=200)
plt.show()


rand = Animate('Torque')
rand.start()

关于python - Matplotlib 动画不在类内更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51928071/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com