python读取出口数据并实时绘图
时间: 2023-08-11 21:20:54 浏览: 227
要实时绘制数据,可以使用 Python 的 matplotlib 库。以下是读取出口数据并实时绘图的示例代码:
```python
import serial
import matplotlib.pyplot as plt
ser = serial.Serial('COM3', 115200) # 根据实际情况修改串口号和波特率
plt.ion() # 开启交互模式
fig, ax = plt.subplots()
while True:
data = ser.readline().decode().strip() # 读取一行数据并转换为字符串
if data:
x, y, z = map(float, data.split(',')) # 解析数据
ax.scatter(x, y, c='r') # 绘制散点图
ax.set_xlim([-10, 10]) # 设置坐标轴范围
ax.set_ylim([-10, 10])
fig.canvas.draw() # 绘制图形
plt.pause(0.001) # 暂停一段时间,等待下一次更新
```
其中,`COM3` 是串口号,`115200` 是波特率,需要根据实际情况修改。`plt.ion()` 用于开启交互模式,`fig, ax = plt.subplots()` 创建一个画布和一个子图,`ax.scatter(x, y, c='r')` 绘制散点图,`ax.set_xlim([-10, 10])` 和 `ax.set_ylim([-10, 10])` 分别设置 X 轴和 Y 轴的范围。`fig.canvas.draw()` 用于绘制图形,`plt.pause(0.001)` 暂停一段时间,等待下一次更新。每次读取到数据后,解析出 X、Y、Z 三个数据,并绘制在图形上。由于开启了交互模式,所以图形会实时更新。
阅读全文
相关推荐


















