首页 > 解决方案 > 使用 matplotlib 平滑动画

问题描述

昨天我开始了学习如何为函数制作动画来为我的工作做一些小项目的旅程。现在,我正在尝试编写一个简单的线性方程图,一次只显示一个点

from itertools import count
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

plt.style.use('seaborn-paper')

x_vals = []
y_vals = []
index = count()

def animate(i):
   x_vals = []
   y_vals = []
   x_vals*= 0
   y_vals*= 0
   var=next(index)
   x_vals.append(var*0.05 % 10)
   y_vals.append(var*0.05 % 10)
   plt.cla()
   plt.xlim(0,10)
   plt.ylim(0,10)
   plt.scatter(x_vals,y_vals)

ani = FuncAnimation(plt.gcf(), animate, interval=1)
plt.tight_layout()
plt.show()

请记住,对于我正在尝试做的事情,这是一个超级粗略的解决方案。我的问题是:有没有办法平滑我的点动画,使它看起来不波涛汹涌?

标签: pythonmatplotlibinterpolation

解决方案


我找到了一种简化代码的方法,可以帮助您加快速度。将 index 作为 frames 参数的函数传递无疑会提高速度。

index = count()

def animate(i):
   var = next(index)
   v = var*0.05 % 10
   plt.cla()
   plt.xlim(0,10)
   plt.ylim(0,10)
   plt.scatter(v,v)

ani = FuncAnimation(plt.gcf(), animate, frames = index, interval = 1)
plt.tight_layout()
plt.show()

推荐阅读