我知道这可能是一个老话题,我在Google上搜索了很多相关主题,但还没有找到有用的信息。我试图从微控制器板获取数据,并在计算机上用Python在3D中绘制数据。我使用PySerial库来实现它,现在我能够从端口接收数据。我现在面临的障碍是我需要在“实时”中绘制这些点(由x,y,z组成),这意味着一旦生成图形,它将保持不变并继续用新点进行更新。
最初我试过plt.show()但它没有用,因为它只在循环完成后显示整个图形,然后我尝试使用plt.draw(),运行时似乎有点奇怪因为GUI弹出窗口在一段时间后总是变得“没有响应”。
我在Window上使用Python 2.7.5。
以下是我绘制一个点的代码:
import serial
import sys
import Queue
import threading
import scipy.io
import numpy as num
from mpl_toolkits.mplot3d import *
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
ser = serial.Serial(port='COM6',timeout=10, baudrate= 57600,bytesize=serial.EIGHTBITS,)
flag = ser.isOpen()
print flag # check if it's opened
# draw the frame
x1 = [164, 94, 0, -100.5]
x2 = [164, 94, 0, -100.5]
y1= [-72.5, -103.5, -103.5, -134.5]
y2= [72.5, 103.5, 103.5, 134.5]
z1 = [112, 60, 3, 3]
z2 = [112, 60, 3, 3]
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
ax.plot(x1, y1, z1, color = 'b')
ax.plot(x2, y2, z2, color = 'r')
plt.hold(True)
while True:
my_list = ser.read(9999) # read 9999 byte
if (ser.isOpen() == False):
break
n = ser.inWaiting() # read the number of chars in the receiver buffer,
# after testing, I found that the max value of n is 4096
if n == 0:
pass
my_list = my_list.split('+00') # split out "+00", make my_list become a list
for item in my_list:
# remove space
if item == '':
my_list.remove(item)
else:
item = float(item) # convert to float type
pass
ax = fig.gca(projection='3d') # to work in 3d
x = my_list.pop(0) # pop the first element in list to x
Floatx= float(x)
y = my_list.pop(0)
Floaty= float(y)
z = my_list.pop(0)
Floatz= float(z)
ax.scatter(Floatx, Floaty, Floatz)
ax.set_xlabel('x label')
ax.set_ylabel('y label')
ax.set_zlabel('z label')
plt.show()
ser.close()
任何建议和建议将不胜感激!谢谢! :)