使用Python繪制實時的動態(tài)折線圖
最近在做視覺應(yīng)用開發(fā),有個需求需要實時獲取當(dāng)前識別到的位姿點位是否有突變,從而確認是否是視覺算法的問題,發(fā)現(xiàn)Python的Matplotlib進行繪制比較方便。
import matplotlib.pyplot as plt import random import numpy as np import time import os import csv
1.數(shù)據(jù)繪制
def draw_data(): index = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] x_data = [1, 0.2, 0.3, 4, 0.5, 0.6, 1, 0.8, 0.9, -1] # 創(chuàng)建折線圖 plt.plot(index, x_data, marker='o', color='b', linestyle='-', label='x_data') # 設(shè)置標(biāo)題和標(biāo)簽 plt.title("x_data") plt.xlabel("Index") plt.ylabel("X Data") # 顯示圖例 plt.legend() # 設(shè)置橫坐標(biāo)刻度,使得每個index值都顯示 plt.xticks(index) # 顯示圖形 plt.show()
2.繪制實時的動態(tài)折線圖
雖然可以實時繪制,但會不斷新增新的窗口,導(dǎo)致越到后面越卡頓,后面采用了保存到CSV文件進行分析的方法。
def realtime_data_draw(): ''' 動態(tài)折線圖實時繪制 ''' plt.ion() plt.figure(1) t_list = [] result_list = [] t = 0 while True: if t >= 100 * np.pi: plt.clf() t = 0 t_list.clear() result_list.clear() else: t += np.pi / 4 t_list.append(t) result_list.append(np.sin(t)) plt.plot(t_list, result_list, c='r', ls='-', marker='o', mec='b', mfc='w') ## 保存歷史數(shù)據(jù) plt.plot(t, np.sin(t), 'o') plt.pause(0.1)
3.保存實時數(shù)據(jù)到CSV文件中
將實時的數(shù)據(jù)保存到CSV文件中,通過excel文件繪制折線圖進行分析。
def realtime_data_save_csv(): # 模擬實時生成的軌跡點坐標(biāo) count = 0 # CSV 文件路徑 file_path = 'vision_data/pose.csv' if os.path.exists(file_path): os.remove(file_path) # 寫入表頭并開始寫入數(shù)據(jù) with open(file_path, mode='w', newline='') as file: writer = csv.writer(file) # 寫入表頭 writer.writerow(['Index', 'X', 'Y', 'Z', 'RX', 'RY', 'RZ']) while True: count += 1 x_value = random.uniform(-0.5, 0.5) y_value = random.uniform(-0.5, 0.5) z_value = random.uniform(-0.1, 0.8) rx_value = random.uniform(-3.14, 3.14) ry_value = random.uniform(-3.14, 3.14) rz_value = random.uniform(-3.14, 3.14) # 將生成的數(shù)據(jù)寫入 CSV 文件 writer.writerow([count, x_value, y_value, z_value, rx_value, ry_value, rz_value]) time.sleep(0.05)
到此這篇關(guān)于使用Python繪制實時的動態(tài)折線圖的文章就介紹到這了,更多相關(guān)Python繪制動態(tài)折線圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python3 實現(xiàn)mysql數(shù)據(jù)庫連接池的示例代碼
這篇文章主要介紹了python3 實現(xiàn)mysql數(shù)據(jù)庫連接池的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04