使用Python繪制實時的動態(tài)折線圖
最近在做視覺應用開發(fā),有個需求需要實時獲取當前識別到的位姿點位是否有突變,從而確認是否是視覺算法的問題,發(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')
# 設置標題和標簽
plt.title("x_data")
plt.xlabel("Index")
plt.ylabel("X Data")
# 顯示圖例
plt.legend()
# 設置橫坐標刻度,使得每個index值都顯示
plt.xticks(index)
# 顯示圖形
plt.show()

2.繪制實時的動態(tài)折線圖
雖然可以實時繪制,但會不斷新增新的窗口,導致越到后面越卡頓,后面采用了保存到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():
# 模擬實時生成的軌跡點坐標
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)



到此這篇關于使用Python繪制實時的動態(tài)折線圖的文章就介紹到這了,更多相關Python繪制動態(tài)折線圖內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python3使用logging包,如何把日志寫到系統(tǒng)的rsyslog中
這篇文章主要介紹了python3使用logging包,如何把日志寫到系統(tǒng)的rsyslog中的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09
Python命令行參數(shù)解析包argparse的使用詳解
argparse?是?python?自帶的命令行參數(shù)解析包,可以用來方便的服務命令行參數(shù)。本文將通過示例和大家詳細講講argparse的使用,需要的可以參考一下2022-09-09
在VS Code上搭建Python開發(fā)環(huán)境的方法
這篇文章主要介紹了在VS Code上搭建Python開發(fā)環(huán)境的方法,需要的朋友可以參考下2018-04-04
python 線性回歸分析模型檢驗標準--擬合優(yōu)度詳解
今天小編就為大家分享一篇python 線性回歸分析模型檢驗標準--擬合優(yōu)度詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02

