You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib问题:如何让双折线图共用同一Y轴刻度

同一Y轴刻度绘制双折线时间序列图

问题描述

需要绘制时间序列图,在同一Y轴刻度下展示speed_mph和max_speed两条折线,但当前绘制的折线未共用同一Y轴刻度。

数据示例

Timespeed_mphmax_speed
08:05:02.63900013.8115
08:05:03.64100013.9215

现有绘图代码

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 02:51:12