1

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

This is what I have:

 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()

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.

MoneyBall
  • 2,343
  • 5
  • 26
  • 59

1 Answers1

1

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)

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

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • wow, this didn't work until I realized that there should be a comma after `self.point,` and `self.line,` and it worked. I do get a warning saying: `MatplotlibDeprecationWarning: Using default event loop until function specific to this GUI is implemented warnings.warn(str, mplDeprecation)`. Some say I can use `plt.draw()` before `plt.pause(0.0001)` but didn't work. How do I avoid this warning? – MoneyBall Nov 01 '17 at 13:54
  • The warning tells you what you are doing: You are using the event loop to plot. In this scenario you cannot avoid the warning. A more robust method would of course be to use `FuncAnimation`. There are enough quetions about that around, if you decide to use it. – ImportanceOfBeingErnest Nov 01 '17 at 14:48
  • `FuncAnimation` seems a bit complicated so I think I'm gonna stick with what I have. Thank you! – MoneyBall Nov 01 '17 at 14:49
  • `FuncAnimation` is not complicated. It might even be more intuitive. [This question](https://stackoverflow.com/questions/45025869/how-to-process-images-in-real-time-and-output-a-real-time-video-of-the-result) has the two options compared. Or [this one](https://stackoverflow.com/questions/42722691/python-matplotlib-update-scatter-plot-from-a-function). – ImportanceOfBeingErnest Nov 01 '17 at 15:08