如何绘制实时图形,两个轴都依赖于时间?

2024-09-29 06:23:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个动画显示潜水员跳入水中。在

根据给定的潜水员离水高度h和他的质量m,我在Python中定义了一个计算他接触水的时刻Tc的过程。在

知道他垂直跳跃,X轴是固定的,并且 Y轴服从方程(1/2)gt2+h(g是引力常数)

当时间t在范围内(Tc),X和Y轴显示潜水员的投影时,如何绘制图形?(x是固定的,y依赖于时间t

在图形窗口中,我们应该看到一个从一定高度垂直向下“跳跃”的点,而没有看到投影的线条/痕迹。在

这是我工作的一部分。我不知道在程序中从何处引入Tc

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

# 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, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.empty(n) ; x.fill(1)   # the vertical position is fixed on x-axis
    y = 0.5*g*i^2 + h             # the equation of diver's displacement on y axis

    line.set_data(x, y) 
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
        frames=200, interval=20, blit=True)

plt.show()

编辑:

这是整个节目。我应用并修改了@Mike Muller给出的建议,但没有奏效。我不明白哪里出了问题。希望你能澄清我的疑虑。在

^{pr2}$

Tags: theimport高度plotinitline时间plt
1条回答
网友
1楼 · 发布于 2024-09-29 06:23:52

根据原始问题回答

您需要使用生成器来生成y数据。这是有效的:

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

# 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, = ax.plot([], [], ' o', lw=2)
g = 9.81
h = 2
tc = 200
xs = [1] # the vertical position is fixed on x-axis
ys = [h, h]


# animation function.  This is called sequentially
def animate(y):
    ys[-1] = y
    line.set_data(xs, ys)
    return line,

def get_y():
  for step in range(tc):
    t = step / 100.0
    y = -0.5*g*t**2 + h  # the equation of diver's displacement on y axis
    yield y

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, frames=get_y, interval=100)

plt.show()

enter image description here

综合回答

这应该是有效的:

^{pr2}$

我删除了不需要的线。不需要global。另外,mass在这个项目中从未使用过。在

这是最重要的部分:

def get_y():
     t = 0
     while t <= Tc:
         y = -0.5 * g * t**2 + h 
         yield y
         t += step

你需要增加你的时间。在

相关问题 更多 >