python - 为什么使用 FuncAnimation 绘图时点不移动?

标签 python python-3.x matplotlib matplotlib-animation

我正在尝试从头开始模拟双星系统中行星的运动。为此,我需要能够在动画图中绘制点。在编写整个代码之前,我正在学习使用 pyplot 为绘图制作动画。到目前为止,我还没有成功地制作出移动点的动画。在查看了几个教程和文档后,我得到了以下内容:

import matplotlib
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ax.set_xlim(0,2)
ax.set_ylim(0,2)
line, = plt.plot(0,0,'bo')
def animation(i):
    x=np.linspace(0,2,100)
    y=np.linspace(0,1,100)
    line.set_data(x[i],y[i],'bo')
    return line,
FuncAnimation(fig, animation, frames=np.arange(100),interval=10)
plt.show()

但是这段代码的输出只是 0,0 处的一个点,我不明白我可能做错了什么。

最佳答案

为了使您的示例正常工作,您必须更改两件事:

  1. FuncAnimation 的返回值存储在某处。否则,您的动画会在 plt.show() 之前被删除。
  2. 如果不想画线而只想画点,请在动画中使用plt.plot
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ax.set_xlim(0,2)
ax.set_ylim(0,2)
line, = plt.plot(0,0,'bo')
def animation(i):
    x=np.linspace(0,2,100)
    y=np.linspace(0,1,100)
    plt.plot(x[i],y[i],'bo')
    return line,

my_animation=FuncAnimation(fig, animation, frames=np.arange(100),interval=10)
plt.show()

如果你只想在图表上有一个移动点,则必须设置 blit=True 并从 animation 中的 plot.plot 返回结果:

from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ax.set_xlim(0,2)
ax.set_ylim(0,2)
line, = plt.plot(0,0,'bo')
def animation(i):
  x=np.linspace(0,2,100)
  y=np.linspace(0,1,100)
  return plt.plot(x[i],y[i],'bo')

my_animation=FuncAnimation(
    fig,
    animation,
    frames=np.arange(100),
    interval=10,
    blit=True
)
plt.show()

此外,您可能想要删除 (0,0) 处的点,并且不想为每个动画帧计算 xy:

from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

ax.set_xlim(0,2) 
ax.set_ylim(0,2) 

x=np.linspace(0,2,100) 
y=np.linspace(0,1,100) 

def animation(i):
  return plt.plot(x[i], y[i], 'bo')

my_animation=FuncAnimation(
    fig,
    animation,
    frames=np.arange(100),
    interval=10,
    blit=True
)
plt.show()

关于python - 为什么使用 FuncAnimation 绘图时点不移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63061594/

相关文章:

python-3.x - 有没有办法缩短python中的if-elif-else语句?

python - 使用内部连接连接两个数据框

Python __future__ 在特定模块之外

python - 如何获取pandas中两列之间的日期范围信息

python - 更改 GUI 库 : QT, wxPython...还有什么?

Python更改异常可打印输出,例如重载__builtins__

python - 如何在字符串中搜索单词并根据匹配的大小写进行不同的打印?

python - Git-Bash 正在插入环境变量

python - 在 Ubuntu : ImportError 上安装 matplotlib

python - 消除小于某个指定数量阈值的连接像素数量