如何在每次迭代时更新Matplotlib pyplot [英] How to update matplotlib pyplot on every iteration

查看:55
本文介绍了如何在每次迭代时更新Matplotlib pyplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 rospy 来获取我的机器人位置的数据并实时绘制它.

I am using rospy to get data of my robot's position and plot this in real time.

这就是我所拥有的:

 self.plot_pose()

 def plot_pose(self):
     plt.plot(self.pose[0], self.pose[1], 'o', color='green')
     plt.plot([self.pose[0], self.pose[0] - 0.5*np.cos(self.pose[2])],
              [self.pose[1], self.pose[1] + 0.5*np.sin(self.pose[2])],
              'k-', color='red', lw=2)

     plt.show(block=False)
     plt.pause(0.0001)

不幸的是,这并没有抹去情节,而是覆盖了一切.所以我尝试使用

Unfortunately this doesn't erase the plot but overlays everything. So I tried using

plt.clf()
plt.cla()

第一个给我贬值错误,第二个由于某种原因给我一个空白图.我正在使用 python2.7 和 rospy 库.

the first one gives me deprecation error and the second one gives me a blank plot for some reason. I am using python2.7 and rospy library.

关于如何更新情节的任何建议将不胜感激.

Any suggestions on how to update the plot would be greatly appreciated.

推荐答案

与动画一样.尽量避免每次交互都创建新图,而是更新旧图.

This is the same as usual with animations. Try to avoid creating new plots every interation and instead update the old one.

self.point, = plt.plot([],[], 'o', color='green')
self.line, =  plt.plot([],[], ls="-", color='red', lw=2)
plt.show(block=False)
self.plot_pose()

def plot_pose(self):
    self.point.set_data(self.pose[0], self.pose[1])
    self.line.set_data([self.pose[0], self.pose[0] - 0.5*np.cos(self.pose[2])],
                       [self.pose[1], self.pose[1] + 0.5*np.sin(self.pose[2])])

    plt.pause(0.0001)

如果点在图的范围之外,则可能需要调整图的限制( plt.xlim() plt.ylim()).

You may need to adjust the limits of the plot (plt.xlim(), plt.ylim()) if the points are outside of it.

这篇关于如何在每次迭代时更新Matplotlib pyplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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