how can i get the plot data in realtime?

孤街浪徒 提交于 2021-01-29 20:25:08

问题


This is the code which the data acquired via the 'COM5' Port, using the arduino card.the problem is that I can't visualize my data in real time, it's like there is no acquisition. I need your help and thanks in advance.

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()

回答1:


Here is some starter code which I used to plot random real-time data, all while continually updating the single figure (NOTE: This code is for Matplotlib not Plotly and this code was run in 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

For your data, you would be appending your timestamp to the xData list (although the axes can be messy with text labels, so I do recommend a numeric x axis instead - which Matplotlib automatically scales) and appending your temperature from the serial port read to yData.



来源:https://stackoverflow.com/questions/65348627/how-can-i-get-the-plot-data-in-realtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!