【发布时间】:2018-03-20 18:20:47
【问题描述】:
我正在尝试使用matplotlib 创建动画情节。当我为 X 值使用整数时,它按预期工作:
#!/usr/bin/env python
import os
import random
import numpy as np
from datetime import datetime as dt, timedelta
from collections import deque
import matplotlib.pyplot as plt # $ pip install matplotlib
import matplotlib.animation as animation
%matplotlib notebook
npoints = 30
x = deque([0], maxlen=npoints)
y = deque([0], maxlen=npoints)
fig, ax = plt.subplots()
[line] = ax.plot(x, y)
def get_data():
t = random.randint(-100, 100)
return t * np.sin(t**2)
def data_gen():
while True:
yield get_data()
def update(dy):
x.append(x[-1] + 1)
y.append(dy)
line.set_data(x, y)
ax.relim()
ax.autoscale_view(True, True, True)
return line, ax
plt.rcParams['animation.convert_path'] = 'c:/bin/convert.exe'
ani = animation.FuncAnimation(fig, update, data_gen, interval=500, blit=True)
#ani.save(os.path.join('C:/','temp','test.gif'), writer='imagemagick', fps=30)
plt.show()
这会产生以下动画:
但是,一旦我尝试使用 datetime 值作为 x 值 - 情节是空的:
npoints = 30
x = deque([dt.now()], maxlen=npoints) # NOTE: `dt.now()`
y = deque([0], maxlen=npoints)
fig, ax = plt.subplots()
[line] = ax.plot(x, y)
def get_data():
t = random.randint(-100, 100)
return t * np.sin(t**2)
def data_gen():
while True:
yield get_data()
def update(dy):
x.append(dt.now()) # NOTE: `dt.now()`
y.append(dy)
line.set_data(x, y)
ax.relim()
ax.autoscale_view(True, True, True)
return line, ax
plt.rcParams['animation.convert_path'] = 'c:/bin/convert.exe'
ani = animation.FuncAnimation(fig, update, data_gen, interval=1000, blit=True)
#ani.save(os.path.join('C:/','temp','test.gif'), writer='imagemagick', fps=30)
plt.show()
我做错了什么?
PS 我用的是matplotlib 版本:2.1.2
【问题讨论】:
-
你检查过这个答案吗:stackoverflow.com/questions/1574088/…?它涉及在绘制图表之前使用 date2num 将日期时间对象转换为数字。
-
我无法重现此内容。动画按预期显示。
-
@ImportanceOfBeingErnest,谢谢你的链接!我试过
date2num- 情节仍然是空的。日期时间对你有用吗?您使用哪个 matplotlib 版本? -
不是我给你那个链接的,因为我不认为这里需要 date2num 转换。我最初使用 2.2.0 进行了测试,但现在我也使用 2.1.0 进行了测试。两种代码在两个版本中都可以正常工作。
-
@ImportanceOfBeingErnest,感谢您的测试!
标签: python datetime animation matplotlib