python - Matplotlib动画,移动正方形

标签 python animation matplotlib

我正在从文本文件中加载 x、y 坐标和偏航角。这些坐标是正方形中间的坐标,yaw是正方形与x轴的夹角。在我的文本文件中,坐标正在改变。我想制作一个动画,其中方 block 将移动(遵循文件中的坐标)并具有精确的偏航角。一个动画刻度应该代表一个方 block 运动。我试过这段代码,但它非常糟糕,无法正常工作。有任何想法吗?谢谢你。现在,我使用左下角而不是正方形的中间。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib as mpl
from matplotlib import animation

file_name = "Crobot_test_log.txt"
x = np.loadtxt(file_name, usecols=(0,))
y = np.loadtxt(file_name, usecols=(1,))
yaw = np.loadtxt(file_name, usecols=(2,))
#x = [0,1,2]
#y = [0,1,2]
#yaw = [0.0,0.5,1.3]
fig = plt.figure()
plt.axis('equal')
plt.grid()
ax = fig.add_subplot(111)
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
patch = patches.Rectangle((x[0],y[0]),1.2,1.0,fc ='y',angle = -np.rad2deg(yaw[0]))

def init():
    ax.add_patch(patch)
    return patch,
def animate(i):
    patch = patches.Rectangle((x[i],y[i]),1.2,1.0,fc ='y',angle = -np.rad2deg(yaw[i]))
    return patch,
anim = animation.FuncAnimation(fig, animate,
                               init_func=init,
                               frames=360,
                               interval=1,
                               blit=True)
plt.show()

最佳答案

不是在 animate 中创建一个新的 Rectangle,而是使用 set_* 方法来修改现有的 patch:

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

x = [0, 1, 2]
y = [0, 1, 2]
yaw = [0.0, 0.5, 1.3]
fig = plt.figure()
plt.axis('equal')
plt.grid()
ax = fig.add_subplot(111)
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)

patch = patches.Rectangle((0, 0), 0, 0, fc='y')

def init():
    ax.add_patch(patch)
    return patch,

def animate(i):
    patch.set_width(1.2)
    patch.set_height(1.0)
    patch.set_xy([x[i], y[i]])
    patch._angle = -np.rad2deg(yaw[i])
    return patch,

anim = animation.FuncAnimation(fig, animate,
                               init_func=init,
                               frames=len(x),
                               interval=500,
                               blit=True)
plt.show()

关于python - Matplotlib动画,移动正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31921313/

相关文章:

Python-GNUPG加密文件无法用私钥解密

ios - React-Native 不支持的布局动画

javascript - HTML5/CSS3 - 除了 z-index 之外的深度替代方案?

Android TranslationAnimation 无法正常工作

python - 在 matplotlib 子图中显示 LineCollections

python - Matplotlib:仅在可用时才使用 TeX

python - 用于测试多个字符串中的多个子字符串的算法

python - 删除换行符前的空格

python - 如何创建一个对象,并从 POST 中的 id 链接到嵌套对象

python-3.x - 是否可以使用 Matplotlib 创建 2 边条形图