2

我试图从头开始模拟双星系统中行星的运动。为此,我需要能够在动画图中绘制点。在对整个事情进行编码之前,我正在学习使用 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 的一个点,我不明白我可能做错了什么。

4

1 回答 1

2

为了使您的示例起作用,您必须更改两件事:

  1. FuncAnimation从某处存储返回值。否则你的动画会在plt.show().
  2. 如果不想画线而只想画点,请plt.plot使用animation
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()

如果您只想在图形上有一个移动点,您必须设置并从in 中blit=True返回结果:plot.plotanimation

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) 处的点,并且您不想为每个动画帧计算x和:y

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()
于 2020-07-23T20:07:30.690 回答