ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
1

How to have matplotlib animation of message?

asked 2018-11-27 09:35:23 -0600

lidar_help gravatar image

Hi, I'm completely new to both ROS and not that good at programming generally so this will probably have an easy solution. But how do you use matplotlib to visualize something that happens inside the callback function? You can't put the lines inside callback function since it will error and say "main thread is not in main loop".

The code I have is below, I want to visualize the scan ranges from a lidar with matplotlib. How do I get a continually updating figure for the scan ranges?

#! /usr/bin/env python
   import rospy
   import numpy as np
   import matplotlib.pyplot as plt
   import matplotlib.animation as animation
   import random
   from sensor_msgs.msg import LaserScan

   x = np.linspace(0, 2* np.pi, 100)
   y=np.random.random_integers(1, 100, 100)

   plt.ion()
   fig = plt.figure()
   ax = fig.add_subplot(111)
   line1, = ax.plot(x, y, 'b-')
   def callback(scan):
       distance_list = scan.ranges
       print(distance_list)
       print("scan angle min", scan.angle_min)
       print("scan angle incr", scan.angle_increment)
       print("scan angle max", scan.angle_max)
       line1.set_ydata(distance_list)
       fig.canvas.draw()

   rospy.init_node('laser_subscriber')
   sub = rospy.Subscriber('\scan', LaserScan, callback)

   rospy.spin()
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2019-06-11 09:36:09 -0600

ChuiV gravatar image

One solution I've used in the past is to use the callback to update the value of a global (or class variable) that the main function can access. Then have a loop in your main thread running that grabs that data and plots it. This way the rate that you can handle callbacks is not limited by how slow matplotlib is.

edit flag offensive delete link more

Question Tools

Stats

Asked: 2018-11-27 09:35:23 -0600

Seen: 1,199 times

Last updated: Jun 11 '19