我想以快速更新的方式實時繪制。
我擁有的資料:
- 通過串行埠以 62.5 Hz 到達
- 資料對應于 32 個傳感器(因此繪制 32 條線與時間)。
- 32 點 *62.5Hz = 2000 點/秒
我當前的繪圖回圈的問題是它的運行速度低于 62.5[Hz],這意味著我錯過了一些來自串行埠的資料。
我正在尋找任何解決這個問題的方法,它允許:
- 保存所有來自串口的資料。
- 繪制資料(甚至跳過幾個點/使用平均值/消除舊點并只保留最新的點)
這是我的代碼,我使用隨機資料來模擬串口資料。
import numpy as np
import time
import matplotlib.pyplot as plt
#extra plot debugging
hz_ = [] #list of speed
time_=[] #list for time vs Hz plot
#store all data generated
store_data = np.zeros((1, 33))
#only data to plot
to_plot = np.zeros((1, 33))
#color each line
colours = [f"C{i}" for i in range (1,33)]
fig,ax = plt.subplots(1,1, figsize=(10,8))
ax.set_xlabel('time(s)')
ax.set_ylabel('y')
ax.set_ylim([0, 300])
ax.set_xlim([0, 200])
start_time = time.time()
for i in range (100):
loop_time = time.time()
#make data with col0=time and col[1:11] = y values
data = np.random.randint(1,255,(1,32)).astype(float) #simulated data, usually comes in at 62.5 [Hz]
data = np.insert(data, 0, time.time()-start_time).reshape(1,33) #adding time for first column
store_data = np.append(store_data, data , axis=0)
to_plot = store_data[-100:,]
for i in range(1, to_plot.shape[1]):
ax.plot(to_plot[:,0], to_plot[:,i],c = colours[i-1], marker=(5, 2), linewidth=0, label=i)
#ax.lines = ax.lines[-33:] #This soluition speeds it up, to clear old code.
fig.canvas.draw()
fig.canvas.flush_events()
Hz = 1/(time.time()-loop_time)
#for time vs Hz plot
hz_.append(Hz)
time_.append( time.time()-start_time)
print(1/(time.time()-loop_time), "Hz - frequncy program loops at")
#extra fig showing how speed drops off vs time
fig,ax = plt.subplots(1,1, figsize=(10,8))
fig.suptitle('Decreasingn Speed vs Time', fontsize=20)
ax.set_xlabel('time(s)')
ax.set_ylabel('Hz')
ax.plot(time_, hz_)
fig.show()

我也在使用時嘗試過
ax.lines = ax.lines[-33:]
洗掉舊點,這加快了繪圖速度,但仍然比我獲取資料的速度慢。

任何確保我收集所有資料并繪制一般趨勢線(所以即使不是所有點)的庫/解決方案都可以。也許可以并行運行獲取資料和繪圖的東西?
uj5u.com熱心網友回復:
您可以嘗試有兩個單獨的行程:
- 一種用于獲取和存盤資料
- 一種用于繪制資料
下面有兩個基本的腳本來理解這個想法。您首先運行gen.py它開始生成數字并將它們保存在檔案中。然后,在同一目錄中,您可以運行plot.py它將讀取檔案的最后一部分并更新 Matplotlib 圖。
這是gen.py生成資料的腳本:
#!/usr/bin/env python3
import time
import random
LIMIT_TIME = 100 # s
DATA_FILENAME = "data.txt"
def gen_data(filename, limit_time):
start_time = time.time()
elapsed_time = time.time() - start_time
with open(filename, "w") as f:
while elapsed_time < limit_time:
f.write(f"{time.time():30.12f} {random.random():30.12f}\n") # produces 64 bytes
f.flush()
elapsed = time.time() - start_time
gen_data(DATA_FILENAME, LIMIT_TIME)
這是plot.py繪制資料的腳本(從
請注意,我還包含并注釋掉了我用來生成上述影片 GIF 的代碼部分。
我相信這應該足以讓你繼續前進。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/494395.html
標籤:Python 麻木的 matplotlib
