我用这个问题制作了一个像这样的动画散点图:
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.collections import PathCollection
df = pd.DataFrame({"x": [1, 2, 6, 4, 5, 6], "y": [1, 4, 36, 16, 25, 36]})
plt.ion()
fig: plt.Figure = plt.figure
ax = fig.subplots()
path_collection: PathCollection = ax.scatter(df.loc[0:2, "x"], df.loc[0:2, "y"])
# Note: I don't use pandas built in DataFrame.plot.scatter function so I can get the PathCollection object to later change the scatterpoints.
fig.canvas.draw()
path_collection.set_offsets([[row.x, row.y] for index, row in df.loc[3:].iterrows()])
# Due to the format of offset (array-like (N,2)) this seems to be the best way to provide the data.
fig.canvas.draw()
这很好用,但我想在 x 轴上有时间,所以我尝试将上面的代码更改为:
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.collections import PathCollection
df = pd.DataFrame({'time': [pd.Timestamp('2021-02-04 00:00:01'),
pd.Timestamp('2021-02-04 00:00:02'),
pd.Timestamp('2021-02-04 00:00:10'),
pd.Timestamp('2021-02-04 00:00:05'),
pd.Timestamp('2021-02-04 00:00:06'),
pd.Timestamp('2021-02-04 00:00:08')],
'y': [5, 6, 10, 8, 9, 10]})
fig: plt.Figure = plt.figure()
ax = fig.subplots()
sc: PathCollection = ax.scatter(df.loc[0:2, "time"], df.loc[0:2, "y"])
fig.canvas.draw()
sc.set_offsets([[row.time, row.y] for index, row in df.loc[3:].iterrows()])
fig.canvas.draw()
倒数第二行抛出此错误:
TypeError: float() argument must be a string or a number, not 'Timestamp'
. 这似乎是由于将其PathCollection
存储_offsets
为不能包含Timestamp
. 所以我想知道,是否有一种解决方法可以用时间轴为散点设置动画?
提前致谢。