Matplotlib问题:如何让双折线图共用同一Y轴刻度
同一Y轴刻度绘制双折线时间序列图
问题描述
需要绘制时间序列图,在同一Y轴刻度下展示speed_mph和max_speed两条折线,但当前绘制的折线未共用同一Y轴刻度。
数据示例
| Time | speed_mph | max_speed |
|---|---|---|
| 08:05:02.639000 | 13.81 | 15 |
| 08:05:03.641000 | 13.92 | 15 |
现有绘图代码
plt.plot(df["timestamp"], df["speed_mph"], label="speed_mph") plt.plot(df["timestamp"], df["max_speed_mph"], label="max_speed_mph") plt.xlabel("Time") plt.ylabel("Speed (mph)") plt.title("Speed vs Time") plt.legend() plt.show()
解决方案
核心问题是列名不匹配:数据中的列名为max_speed,但代码中误用了max_speed_mph,导致读取的列数据异常,进而引发Y轴刻度不一致。此外需确保时间列和数值列的数据类型正确。
修正后的代码
# 可选:先确认数据列名和类型,排查异常 print(df.columns) print(df[["speed_mph", "max_speed"]].dtypes) # 绘制同一Y轴的双折线图 plt.plot(df["Time"], df["speed_mph"], label="speed_mph") plt.plot(df["Time"], df["max_speed"], label="max_speed") plt.xlabel("Time") plt.ylabel("Speed (mph)") plt.title("Speed vs Time") plt.legend() # 可选:自动调整X轴标签避免重叠 plt.xticks(rotation=45) plt.tight_layout() plt.show()
额外说明
- 如果确实存在
max_speed_mph列,需检查该列数据是否为有效数值(比如是否有大量NaN或异常值),异常数据会导致Matplotlib自动调整Y轴范围,看起来像是双Y轴。 - Matplotlib默认情况下,多次调用
plt.plot()会使用同一个坐标轴,只要数据正常,就会共享Y轴刻度。
内容的提问来源于stack exchange,提问作者Brandon
相关产品推荐
相关产品推荐

