我要自动更新X轴日期时间限制。在set_xlim
函数中使用__init__
时可以使用,但是在__call__
函数中使用时,同一命令无效。
代码:
import datetime
import time
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.animation import FuncAnimation
def data():
target_time = datetime.datetime.now()
n=0
while True:
target_time = target_time + datetime.timedelta(seconds=1)
x = target_time
y=np.sin(n)*10
yield (x, y)
n+=0.05
time.sleep(2)
class Update(object):
def __init__(self, ax):
self.x=[datetime.datetime.now()]
self.y=[0]
self.line, = ax.plot(self.x, self.y, 'k-')
self.ax = ax
# Set up plot parameters
now = self.x[0]
minxlim = now - datetime.timedelta(seconds=60)
maxxlim = now + datetime.timedelta(seconds=60)
print(minxlim)
self.ax.set_xlim(left=minxlim, right=maxxlim) # it's works
self.ax.set_ylim(-15, 15)
self.ax.grid(True)
self.counter=0
def init(self):
self.line.axes.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))
return self.line,
def __call__(self, args):
self.counter += 1
i = self.counter
win = 60
imin = max(0, i - win)
self.x.append(args[0])
self.y.append(args[1])
xdata = self.x[imin:i]
ydata = self.y[imin:i]
self.line.set_data(xdata, ydata)
self.line.set_color("red")
now = xdata[-1]
minxlim = now - datetime.timedelta(seconds=60)
maxxlim = now + datetime.timedelta(seconds=60)
self.ax.set_xlim(left=minxlim, right=maxxlim) # not work
self.ax.relim()
self.ax.autoscale_view()
return self.line,
fig, ax = plt.subplots()
ud = Update(ax)
anim = FuncAnimation(fig, ud, frames=data,init_func=ud.init,interval=1000, blit=True)
plt.show()
运行此命令时,即使限制应更改每帧,它仍看起来像初始X轴。
答案 0 :(得分:0)
划线会更改轴的内容,而不是装饰器。这意味着像刻度和标签这样的装饰器在整个过程中都保持不变。
由于您的动画无论如何还是很慢的,因此不需要发条。因此,您可以将其关闭,
FuncAnimation(..., blit=False)