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

使用matplotlib+pandas实现指定规则多Y轴绘图的方法咨询

多Y轴绘图问题解答

ax.twinx()使用逻辑说明

  • 每次调用ax.twinx()都会创建一个与原有坐标轴共享X轴的新坐标轴实例,默认新实例的Y轴会渲染在画布右侧
  • 关于是否每个独立Y轴都需要单独生成twinx()实例:是的,每一组需要独立刻度的Y轴都需要单独的twinx()实例;如果多个曲线数值范围接近可以共用Y轴,不需要为每个曲线单独生成实例。你的需求里Value1和Value2共用Y轴,所以总共只需要3个坐标轴实例:
    1. 原始ax:承载Temperature,使用默认左侧Y轴
    2. 第一个twinx实例:承载Value1、Value2,使用默认右侧Y轴
    3. 第二个twinx实例:承载Pressure,使用偏移后的右侧Y轴

原有代码问题原因

直接多次调用twinx()但没有对新增的Y轴做位置偏移配置,所有右侧Y轴都重叠在同一个位置,所以出现挤在一起的展示问题。

修正后可运行代码

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 生成模拟数据
rows,cols = 8760,4
data = np.random.rand(rows,cols) 
tidx = pd.date_range('2019-01-01', periods=rows, freq='H') 
df = pd.DataFrame(data, columns=['Temperature','Value1','Pressure','Value2'], index=tidx)

# 创建画布和基础坐标轴
fig, ax = plt.subplots(figsize=(25,8))
plt.title('多Y轴曲线图')

# 第一个独立Y轴:Temperature(左侧默认轴)
plot1, = ax.plot(df.index, df.Temperature, color='tab:blue')
ax.set_xlabel('日期')
ax.set_ylabel('Temperature', color=plot1.get_color())
ax.tick_params(axis='y', labelcolor=plot1.get_color())

# 第二个独立Y轴:Value1和Value2共用(默认右侧轴)
ax2 = ax.twinx()
plot2, = ax2.plot(df.index, df.Value1, color='tab:red')
plot3, = ax2.plot(df.index, df.Value2, color='tab:orange')
ax2.set_ylabel('Value系列', color=plot2.get_color())
ax2.tick_params(axis='y', labelcolor=plot2.get_color())

# 第三个独立Y轴:Pressure(偏移后的右侧轴)
ax3 = ax.twinx()
# 向右偏移Y轴位置,避免和ax2的轴重叠,1.2表示在坐标轴宽度1.2倍的位置
ax3.spines.right.set_position(("axes", 1.2))
plot4, = ax3.plot(df.index, df.Pressure, color='tab:green')
ax3.set_ylabel('Pressure', color=plot4.get_color())
ax3.tick_params(axis='y', labelcolor=plot4.get_color())

# 添加图例
plt.legend([plot1, plot2, plot3, plot4], list(df.columns), loc='upper right')

# 调整布局
plt.tight_layout()

# 展示图像
plt.show()

运行上述代码后,三个Y轴会分别排布在左侧、右侧默认位置、右侧偏移位置,不会出现重叠问题,Value1和Value2会共用同一套Y轴刻度。

内容的提问来源于stack exchange,提问作者bbartling

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 10:54:03