0

I am trying to plot real-time data coming from other node in ros using matplotlib, but whenever i am running the code, it only shows empty graphs with out plotting any data on it. what might the problem please ?

Here is my code:

import rospy
from datetime import datetime
from std_msgs.msg import Float64
from geometry_msgs.msg import Vector3
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
plt.show()

i = 0
xs = []
ys = []
time = []

#def callback0(msg):

def callback1(msg):
    global i
    time.append(i)
    xs.append(msg.x)
    ys.append(msg.y)

    #plot time vs xs
    ax.plot(time, xs)
    print(len(time), len(xs))
    ax.set_xlim(left= max(0, i-50), right= i+50)
    plt.draw()
    plt.pause(0.5) #graph keep updating each 1 sec
    i += 1


if __name__ == '__main__':

    rospy.init_node('subscriber' ,anonymous=True)
    #rospy.Subscriber('fchatter', Float64, callback0)
    rospy.Subscriber('vchatter', Vector3, callback1)
    rospy.spin()
Matteo Peluso
  • 452
  • 1
  • 6
  • 23

1 Answers1

0

Try this code

import rospy
from datetime import datetime
from std_msgs.msg import Float64
from geometry_msgs.msg import Vector3
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)


i = 0
xs = []
ys = []
time = []

#def callback0(msg):

def callback1(msg):
    global i
    time.append(i)
    xs.append(msg.x)
    ys.append(msg.y)

#plot time vs xs
    ax.plot(time, xs)
    print(len(time), len(xs))
    ax.set_xlim(left= max(0, i-50), right= i+50)
    plt.draw()
    plt.pause(0.5) #graph keep updating each 1 sec
    i += 1
    plt.show()


if __name__ == '__main__':
    rospy.init_node('subscriber' ,anonymous=True)
    #rospy.Subscriber('fchatter', Float64, callback0)
    rospy.Subscriber('vchatter', Vector3, callback1)
    rospy.spin()
Amjad
  • 3,110
  • 2
  • 20
  • 19