这篇教程使用Python绘制实时的动态折线图写得很实用,希望能帮到您。 最近在做视觉应用开发,有个需求需要实时获取当前识别到的位姿点位是否有突变,从而确认是否是视觉算法的问题,发现Python的Matplotlib进行绘制比较方便。 import matplotlib.pyplot as pltimport randomimport numpy as npimport timeimport osimport csv
1.数据绘制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] # 创建折线图 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.绘制实时的动态折线图虽然可以实时绘制,但会不断新增新的窗口,导致越到后面越卡顿,后面采用了保存到CSV文件进行分析的方法。 def realtime_data_draw(): ''' 动态折线图实时绘制 ''' 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') ## 保存历史数据 plt.plot(t, np.sin(t), 'o') plt.pause(0.1) 
3.保存实时数据到CSV文件中将实时的数据保存到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) # 写入表头并开始写入数据 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) # 将生成的数据写入 CSV 文件 writer.writerow([count, x_value, y_value, z_value, rx_value, ry_value, rz_value]) time.sleep(0.05) 


到此这篇关于使用Python绘制实时的动态折线图的文章就介绍到这了,更多相关Python绘制动态折线图内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站! Python实现批量替换Excel中字符 基于Python制作简易视频播放器 |