Matplotlib动画,移动方块 [英] Matplotlib animation, moving square

查看:189
本文介绍了Matplotlib动画,移动方块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从文本文件加载x,y坐标和偏航角。这些坐标是正方形的中心坐标,而偏航是正方形与x轴的夹角。在我的文本文件中,坐标正在变化。我想制作一个动画,其中正方形将移动(跟随文件中的坐标)并具有精确的偏航角。一个动画滴答应表示一个正方形移动。我尝试过此代码,它非常糟糕,无法正常工作。有任何想法吗?谢谢。现在,我使用左下角而不是正方形的中间。

I am loading x,y coordinates and yaw angle from text file. These coordinates are coordinates of the middle of square, and yaw is an angle of the square with x axis. In my text file coordinates are changing. I want to make an animation in which square will be moving (following coordinates from file) and with exact yaw angle.One animation tick should represent be one square movement. This code I tried, and it is very bad and not working. Any ideas? Thank you. For now, I use left bottom corner not middle of the square.

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 _ * 方法来修改现有的补丁

Instead of creating a new Rectangle in animate, use set_* methods to modify the existing 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()

这篇关于Matplotlib动画,移动方块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆