我试图用python绘制实时数据到计算机。数据来自一个ROS主题,我使用“rospy”订阅主题以获取数据。 这是我写的代码
import rospy
from sensor_msgs.msg import ChannelFloat32
import matplotlib.pyplot as plt
N = 200
i = 0
topic = "chatter"
x = range(N)
lmotor = [0]*N
rmotor = [0]*N
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim([0,N])
ax.set_ylim([-1,1])
line1, = ax.plot(lmotor, 'r-')
line2, = ax.plot(rmotor, 'g')
def plotThrottle(data):
global x, lmotor, rmotor, i
[x[i],lmotor[i],rmotor[i], tmp] = data
line1.set_ydata(lmotor)
line1.set_xdata(x)
line2.set_ydata(rmotor)
line2.set_xdata(x)
fig.canvas.draw()
def callBack(packet):
data = list(packet.values)
plotThrottle(data)
def listner():
rospy.init_node('listener', anonymous=True)
rospy.Subscriber(topic, ChannelFloat32, callBack)
rospy.spin()
if __name__ == '__main__':
listner()
我的问题是,当我用从rostopic获得的数据调用plotThrottle()
时,我得到以下错误。在
但是如果我使用相同的函数并传递代码中生成的一些数据(一些随机数据),绘图就可以了。 我绝对是python的初学者。我搜索了一下这个错误,它说这是因为线程问题。但我不知道如何修复这个代码。如果有人能解释这个问题并帮助修复这个代码,我真的很感激。在
这里有两个线程在运行,罗斯比.斯潘()和顶部.mainloop()(来自Tkinter,在您的案例中是matplotlib的后端)。在
来自this answer:
从this answer:
因此,您可以使用
plt.show(block=True)
来阻止程序关闭,在这种情况下,您将使用Tkinter mainloop,重新绘制画布而不会出现问题。在侦听器功能应该如下所示:
无论如何,对于其他替代方案来说,这似乎是一个解决办法,请再次参阅this answer或简单地使用单独的节点进行绘图,即ros建议的工具,如rqt_graph。在
相关问题 更多 >
编程相关推荐