如何让Matplotlib中温度与湿度曲线相交?
问题分析
你遇到的曲线分离、无法按数值逻辑相交的核心原因是:从串口读取的温度、湿度数据是字符串类型,Matplotlib默认将其视为分类数据而非连续数值,导致两条曲线的Y轴逻辑不统一,呈现出错位分离的状态。
解决方案
针对代码核心问题,做以下关键修改:
- 将读取到的字符串数据转换为浮点型(
float),确保Matplotlib按数值绘制曲线 - 优化数据处理逻辑,避免重复调用
split() - 添加异常捕获,防止串口数据格式异常导致程序崩溃
- 补充图表标签、图例,提升可读性
修改后的代码:
import matplotlib.pyplot as plt from itertools import count from matplotlib.animation import FuncAnimation import serial x = [] line1 = [] # 存储温度数值 line2 = [] # 存储湿度数值 serialPort = serial.Serial(port="COM3", baudrate=115200, bytesize=8, timeout=1, stopbits=serial.STOPBITS_ONE) index = count() def animate(i): if serialPort.in_waiting > 0: try: # 读取并清理串口数据 serialString = serialPort.readline() string = serialString.decode('ascii').strip() # 拆分并转换为数值类型 temp_str, humi_str = string.split(' ') temp = float(temp_str) humi = float(humi_str) line1.append(temp) line2.append(humi) x.append(next(index)) # 限制数据长度,避免内存占用过高 if len(line1) >= 1000: line1.pop(0) line2.pop(0) x.pop(0) except (ValueError, IndexError): # 数据格式错误时跳过,避免程序崩溃 print("串口数据格式异常,跳过当前数据") plt.cla() # 绘制数值曲线 plt.plot(x, line1, label='Temperature') plt.plot(x, line2, label='Humidity') # 添加图表元素 plt.xlabel('Time') plt.ylabel('Value') plt.legend() plt.tight_layout() ani = FuncAnimation(plt.gcf(), animate, interval=400) plt.show()
额外说明
- 如果传感器输出整数数据,可将
float()替换为int() strip()用于去除字符串首尾的换行符、空格等冗余字符,避免拆分出错- 异常捕获逻辑可根据需求扩展,比如增加日志记录
内容的提问来源于stack exchange,提问作者Noah Robb
相关产品推荐
相关产品推荐

