A source code which plots subscribed ROS data in real time is proposed in this article.
【Python, ROS】Real time plotting ROS message with matplotlib
Visualizing data in real time is required often for engineers.
▶日本語のページはコチラ(Japanese ver.)
Outline of the implementation
- Subscribe: ROS message (Float64)
- X axis: time
- Y axis: value of the subscribed message
Source code
#!/usr/bin/env python import rospy from std_msgs.msg import Float64 import numpy as np import matplotlib.pyplot as plt import time start_time = 0.0 t_ = 0.0 y_ = 0.0 def callback(msg): print('callback') global start_time global t_ global y_ if start_time>0: t_ = time.time() - start_time y_ = msg.data def graph(): print('realtime_graph') rospy.init_node('realtime_graph', anonymous=True) rospy.Subscriber("/message", Float64, callback) #Initialization of the graph t = [0 for i in range(100)] #Size of X axis y = [0 for k in range(100)] #Size of Y axis plt.ion() plt.figure() plt.title("y") plt.xlabel("time[s]") plt.ylabel("y[-]") plt.ylim(-10, 10) #Min of Y axis, max of Y axis (fixed) plt.grid(True) li, = plt.plot(t, y) global start_time global t_ global y_ start_time = time.time() #Update of the graph while not rospy.is_shutdown(): print('loop') t.append(t_) #Appending a new value in X axis t.pop(0) #Popping the oldest value in X axis y.append(y_) #Appending a new value in Y axis y.pop(0) #Popping the oldest value in Y axis li.set_xdata(t) li.set_ydata(y) plt.xlim(min(t), max(t)) #Min of Y axis, max of Y axis (dynamic) plt.draw() plt.pause(0.1) #Update rate rospy.spin() if __name__ == '__main__': graph()
Ad.
Explanation
- Initialization of the graph with zero is require at the beginning.
- When a new message is subscribed, it is appended, and the oldest value is popped.
- Some global variables are needed because callback is special.
Lastly...
A source code which plots subscribed ROS data in real time is proposed in this article. I hope this article will help you, and you can you use it.
Thanks for reading. Good luck!
P.S.
I found that you don’t need to write such a complicate code above after finish writing this article, and you can just use rqt_plot. It is a helpful tool from ROS.
Ad.
コメント