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

matplotlib如何缩放坐标轴 避免多Y轴绘制的曲线互相覆盖

解决方法

核心问题是a、b两个字段数值范围接近,且默认Y轴适配各自数据范围导致折线在画布上的位置重叠,可通过调整Y轴显示范围+差异化折线样式+错开轴位置的组合方案解决,修改后代码如下:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("plot.csv")

yax1 ='a'
yax2 = 'b'
yax3 = 'c'

# 绘制a对应的左轴,加圆形标记
ax1 = df.plot(x='Date', y=yax1, color='black', figsize=(12,7), legend=False, linestyle='-', marker='o')
ax1.set_ylabel(yax1)
ax1.yaxis.label.set_color('black')
ax1.set_xlabel('Date')    
ax1.set_ylim(8, 18) # 固定a的Y轴范围,避免自适应偏移

plt.subplots_adjust(right=0.85)    

# 绘制b对应的第一个右轴,调整Y轴范围到0-20,和a的范围错开,加三角标记、虚线
ax2 = ax1.twinx()
ax2.spines['right'].set_position(('axes', 1.0))
df[yax2].plot(ax=ax2, color='green', linestyle='--', marker='^')
ax2.set_ylabel(yax2)
ax2.yaxis.label.set_color('green')
ax2.set_ylim(0, 20) # 调整b的Y轴范围,让b的折线落在画布下半区,和a完全错开
ax2.spines['right'].set_color('green')     

# 绘制c对应的第二个右轴,位置再往右偏移,加星型标记
ax3 = ax1.twinx()
ax3.spines['right'].set_position(('axes', 1.15))
df[yax3].plot(ax=ax3, color='red', linestyle='-.', marker='*')
ax3.set_ylabel(yax3)
ax3.yaxis.label.set_color('red')
ax3.spines['right'].set_color('red')     

# 统一设置图例,避免重复
ax3.legend([ax1.get_lines()[0], ax2.get_lines()[0], ax3.get_lines()[0]],[yax1, yax2, yax3], loc='upper left')

plt.tight_layout()
plt.show()

上述代码通过固定a和b的Y轴范围让两条折线分别落在画布上下半区,同时搭配不同的线型和标记,哪怕数值走势接近也能清晰区分,c的轴额外向右偏移避免和b的轴标签重叠。如果不想调整b的Y轴范围,也可以仅保留差异化线型和标记的修改,也能大幅提升区分度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:57:04