python - 使用 matplotlib 为与时间相关的 LineCollection 设置动画
问题描述
如上所述,我正在尝试为一组随时间变化的数据(位置)设置动画。我希望我的图表只显示位置数据,但随着时间的推移动画位置历史。我从这里的这个例子开始,并让它工作。现在,我希望从左到右绘制线条,而不是整条线的动画。我还需要相对于辅助数据集对线进行着色,我已经能够使用 LineCollection 来完成。
我的代码:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line = LineCollection([], cmap=plt.cm.jet)
line.set_array(np.linspace(0, 2, 1000))
ax.add_collection(line)
x = np.linspace(0, 2, 10000)
y = np.sin(2 * np.pi * (x))
# initialization function: plot the background of each frame
def init():
line.set_segments([])
return line,
# animation function. This is called sequentially
def animate(i, xss, yss, line):
xs = xss[:i]
ys = yss[:i]
points = np.array([xs, ys]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
line.set_segments(segments)
return line,
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, fargs=[x, y, line], init_func=init, frames=200, interval=20)
plt.show()
我创建了一个基本的正弦波数据集,并再次希望为从左到右绘制的线设置动画。现在,LineCollection 被当前 x 位置的线的 y 值着色。最终,这将是从 .csv 文件中提取的位置数据集。
最后,问题。上面的代码运行没有错误,但是没有画线。我可以在我的调试器中看到在每个步骤中都添加了xs
和ys
数组,因此语法似乎可以正常工作,只是没有显示更新的 LineCollection。
我正在开发 macOS Mojave 10.14.6。
解决方案
您的代码是正确的,您绘制的线非常小。这是因为您制作动画的功能由
x = np.linspace(0, 2, 10000) # Note that `num=10000`
y = np.sin(2 * np.pi * (x))
它有 10000 个点,但您只为前 200 个点设置动画。
anim = animation.FuncAnimation(..., frames=200, interval=20)
轻松修复
num_frames = 200
x = np.linspace(0, 2, num_frames)
...
anim = animation.FuncAnimation(..., frames=num_frames, interval=20)
推荐阅读
- docker - 无法在 Windows Server 2019 中以 swarm 入口模式从 docker 容器访问主机及其私有 IP
- java - 使用 Kotlin 开发时的 Android getGlobalApplicationContext()
- python - 刷新 GUI 窗口
- android - 为什么我没有从 Android O 上的 startService 获得非法状态表达式
- python - 单击的信号仅适用于静态方法
- html - 角材料扩展模块不起作用
- xslt-3.0 - 我们如何在 Saxon HE 9 下调用 c# 方法
- android - 检测ScrollView垂直滚动方向
- ios - 如何在 swift 中使用 malloc_zone_statistics 查找我的 iOS 应用程序的堆内存?
- python - 网络爬到一张桌子