首页 > 解决方案 > 如何实时获取绘图数据?

问题描述

这是使用arduino卡通过'COM5'端口获取数据的代码。问题是我无法实时可视化我的数据,就像没有采集一样。我需要你的帮助和提前感谢。

import serial
import time
import matplotlib.pyplot as plt
import cufflinks as cf
from plotly.graph_objs.scatter import Line
from plotly.graph_objs.layout import Font ,XAxis , YAxis ,Legend

from plotly.graph_objs.streamtube import Stream
from plotly.graph_objs import Scatter, Layout,Figure 
from plotly.offline import plot 
arduinoFile = 'COM5'
logFile = 'log.csv'

sensorOutput = [0.0, 0.0]
 
ser = serial.Serial(arduinoFile, baudrate=9600, bytesize=8,
    parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=10)
time.sleep(1)
ser.flushInput()

# empty list to store the data 
my_data = [Scatter(x=[], y=[], name='Sensor 1 temperature', mode='lines', line= Line(color='rgba(250,30,30,0.9)',width=2.5), stream=dict(maxpoints=900)), yaxis='y2')]
 
my_layout = Layout( title='Temperature', xaxis=XAxis(showline=True, linecolor='#bdbdbd', title='Time', showticklabels=True), yaxis=YAxis( showline=True,linecolor='#bdbdbd',title='Temperature [*C]',showticklabels=True),legend=Legend(x=0,y=1), showlegend=True)
 
my_fig = Figure(data=my_data, layout=my_layout)
plot(my_fig, filename='Temperature.html', validate =False)
time.sleep(3)
 
 
timeStart = time.time()
while True:
    for i in range(0, 4, 1) :
        serial_line = ser.readline() # read a byte string
    timeDelay = time.time()-timeStart
    timeStamp = time.strftime("%Y-%m-%d")
    
       
       
    sensorOutputRaw = serial_line.split(','.encode()) # decode byte string into Unicode
    sensorOutputRaw[-1]=sensorOutputRaw[-1].strip()
    sensorOutput[0] = float(sensorOutputRaw[0]) + 0.4  # calibration
    resultString = str(timeDelay)+','+timeStamp+','+ str(sensorOutput[0])
    print(resultString)
    my_file = open(logFile,'a')
    my_file.write(resultString+'\n')
    my_file.close()
    
    time.sleep(50)
 
ser.close()
plt.show()

标签: pythonplotplotlyscatter

解决方案


这是我用来绘制随机实时数据的一些起始代码,同时不断更新单个图形(注意:此代码适用于Matplotlib而不是 Plotly,此代码在 Jupyter Notebook 中运行):

# Import necessary packages
from matplotlib import pyplot as plt
from IPython.display import clear_output
import numpy as np
import time

# Init key variables 
counter = 0
xData = []
yData = []
Ts = 0.25     # Sampling time

# Do the following loop forever
while True:
    clear_output(wait=True)           # Clear the figure
    
    fig = plt.figure(figsize=(12,8))  # Create a new big clean figure
    plt.title('Real Time Data')       # Add a title
    
    xData.append(counter + 1)               # Append new x data (i.e. timestamp)
    yData.append(np.random.random(1)[0])    # Append new y data (i.e. temperature)
    counter += 1
    
    plt.plot(xData, yData)       # Plot the x and y data here (feel free to add plot options)
    plt.title('Real Time Temperature Data')  # Add a title
    plt.xlabel('Timestamp')      # Label axes
    plt.ylabel('Y Axis')
    
    plt.show()                   # Show the figure

    time.sleep(Ts)                # Wait until next time sample

对于您的数据,您会将时间戳附加到xData列表中(尽管轴可能与文本标签混淆,因此我建议使用数字 x 轴 - Matplotlib 自动缩放)并将您的温度从串行端口读取到附加到yData.


推荐阅读