Sta*_*Man 12 python matplotlib animated-gif matplotlib-animation
我使用FuncAnimationMatplotlib Animation 类创建了一个动画绘图,我想将其保存为 .gif 文件。当我运行脚本时,输出看起来正常,如下所示(动画工作正常):
但是,当我尝试使用 ImageMagick 或 PillowWriter 将动画图另存为 .gif 文件时,该图如下图所示:
线条明显粗了很多,总的来说,看起来很糟糕。该问题归因于点(紫色和红色圆圈)。因此,似乎情节是在每一帧上书写的(我认为是这样)。我可以通过将它们全部删除来避免这种情况。但我不想这样做,因为很难看清线条。
这是代码:
line, = ax.plot([], [], color = 'blue', lw=1)
line2, = ax.plot([], [], color = 'red', lw=1)
line3, = ax.plot([], [], color = 'purple', lw=1)
def animate(i):
line.set_data(x1[:i], y1[:i])
line2.set_data(x2[:i], y2[:i])
line3.set_data(x3[:i], y3[:i])
point1, = ax.plot(x1[i], y1[i], marker='.', color='blue')
point2, = ax.plot(x2[i], y2[i], marker='.', color='red')
point3, = ax.plot(x3[i], y3[i], marker='.', color='purple')
return line, line2, line3, point1, point2, point3,
ani = animation.FuncAnimation(fig, animate, interval=20, blit=True, repeat=False, frames=1000, save_count=1000)
ani.save("TLI.gif", writer='imagemagick',fps=60)
Run Code Online (Sandbox Code Playgroud)
这些数组x1, y1, x2, y2, x3, y3都是包含 x、y 坐标的一维数组。那么为什么会发生这种情况呢?为什么当我直接运行 .gif 文件时,它不显示绘图所显示的内容?另外,我该如何解决这个问题?
我也知道这个堆栈溢出问题:matplotlib 动画保存不遵守 blit=True 但它似乎在 plt.show() 中工作得很好,这意味着问题肯定归因于 blitting。然而,阅读该问题的答案并没有解决我的问题,因为这仅指ax.text与通过 绘制的常规点相反ax.plot。
Ind*_*nes 16
看看这是否有效。我没有 Imagemagick 所以我用了 Pillow。
为了防止动画显示堆叠帧(即点轨迹),技巧是清除轴以刷新每个帧。然后为每一帧设置xlim和ylim,并使用以下命令绘制增量线ax.plot(x1[0:i], y1[0:i]...
要提高图像分辨率,请将输出 dpi 设置为合适的值。我尝试了一下并决定使用 300 来获得清晰的线条和轴线/数字。
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
import numpy as np
x1 = np.arange(0, -0.2, -0.002)
y1 = np.arange(0, -0.2, -0.002)
x2 = np.arange(3.9, 3.7, -0.002)
y2 = np.arange(0, 1, 0.01)
x3 = np.arange(0, 1.8, 0.018)
y3 = np.array(x3**2)
fig,ax = plt.subplots()
def animate(i):
ax.clear()
ax.set_xlim(-4,4)
ax.set_ylim(-4,4)
line, = ax.plot(x1[0:i], y1[0:i], color = 'blue', lw=1)
line2, = ax.plot(x2[0:i], y2[0:i], color = 'red', lw=1)
line3, = ax.plot(x3[0:i], y3[0:i], color = 'purple', lw=1)
point1, = ax.plot(x1[i], y1[i], marker='.', color='blue')
point2, = ax.plot(x2[i], y2[i], marker='.', color='red')
point3, = ax.plot(x3[i], y3[i], marker='.', color='purple')
return line, line2, line3, point1, point2, point3,
ani = FuncAnimation(fig, animate, interval=40, blit=True, repeat=True, frames=100)
ani.save("TLI.gif", dpi=300, writer=PillowWriter(fps=25))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21715 次 |
| 最近记录: |