为什么我创建的图表不能互动? (来自arduino的matplotlib中的实时图表)

时间:2017-04-15 09:03:37

标签: python-2.7 matplotlib arduino

enter image description here

我制作了一个旋转箭头的图表,该箭头与从旋转编码器获得的数据相对应。每次我旋转旋钮编码器,它都会带来一个新的图表。事实上,我只想显示图表,随时显示箭头的旋转。我创建的错误代码在哪里?

%matplotlib qt
import serial
import numpy as np
import matplotlib.pyplot as plt
s=[]
plt.ion()
def up():
    fig = plt.figure()
    ax1 = fig.add_subplot(121, polar=True)
    ax1.set_rmax(2.0)
    ax1.set_theta_zero_location("N")
    ax1.set_rticks([])
    plt.title('Angle \n')
    plt.rc('grid', color='black', linewidth=1, linestyle='-')
    ax1.set_xticklabels(['U', 'BL', 'B', 'BD', 'S', 'TG', 'T', 'TL'])
    plt.arrow(ino, 0, 0, 1.55,alpha = 0.75, width = 0.01,ec = 'black', fc = 'blue', lw = 1.25)

while True:
    ino=float(serial.Serial('/dev/ttyUSB0',9600).readline()[10:])/180.*np.pi
    s.append(ino)
    up()
    plt.pause(.000001)
    plt.show()

2 个答案:

答案 0 :(得分:0)

如果你想拥有一个单一的数字,你应该只创建一个单个数字,而不是每次更新一个数字。

在更新功能中,您只需从轴上移除旧箭头并绘制一个新箭头。

%matplotlib qt
import serial
import numpy as np
import matplotlib.pyplot as plt
s=[]
plt.ion()
fig = plt.figure()
ax1 = fig.add_subplot(121, polar=True)
ax1.set_rmax(2.0)
ax1.set_theta_zero_location("N")
ax1.set_rticks([])
plt.title('Angle \n')
plt.rc('grid', color='black', linewidth=1, linestyle='-')
ax1.set_xticklabels(['U', 'BL', 'B', 'BD', 'S', 'TG', 'T', 'TL'])
arrow = plt.arrow(0, 0, 0, 1.55,alpha = 0.75, width = 0.01,ec = 'black', fc = 'blue', lw = 1.25)

def up(ino):
    arrow.remove()
    return plt.arrow(ino, 0, 0, 1.55,alpha = 0.75, width = 0.01,ec = 'black', fc = 'blue', lw = 1.25)

while True:
    ino=float(serial.Serial('/dev/ttyUSB0',9600).readline()[10:])/180.*np.pi
    s.append(ino)
    arrow = up(ino)
    plt.draw()
    plt.pause(.000001)

plt.ioff()
plt.show()

答案 1 :(得分:0)

谢谢!我尝试在您的(@ImportanceOfBeingErnest)代码中添加新变量(inoS)。我不知道它为什么会起作用,但它解决了我的问题......你知道它为什么会起作用吗?

%matplotlib qt
import serial
import numpy as np
import matplotlib.pyplot as plt
from drawnow import *

s=[]
fig = plt.figure()
ax1 = fig.add_subplot(121, polar=True)
ax1.set_rmax(2.0)
ax1.set_theta_zero_location("N")
ax1.set_rticks([])
plt.title('Angle \n')
plt.rc('grid', color='black', linewidth=1, linestyle='-')
ax1.set_xticklabels(['U', 'BL', 'B', 'BD', 'S', 'TG', 'T', 'TL'])
plt.ioff()
arrow = plt.arrow(0, 0, 0, 1.55,alpha = 0.75, width = 0.01,ec = 'black', fc = 'blue', lw = 1.25)
def up(inoS):
    arrow.remove()
    return plt.arrow(-inoS/180.*np.pi, 0, 0, 1.55,alpha = 0.75, width = 0.01,ec = 'black', fc = 'blue', lw = 1.25)

while True:
    ino=serial.Serial('/dev/ttyUSB0',9600)
    inoS=float(ino.readline())
    print inoS
    s.append(inoS)
    arrow=up(inoS)
    plt.draw()
    plt.pause(.000001)
plt.show()