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

如何使Matplotlib双y轴(.twinx)的零点对齐?

解决Matplotlib双y轴零点对齐问题

要让双y轴的零点对齐,核心是让两个轴的数据范围按比例匹配,确保0点处于同一垂直位置。以下是具体实现方法,包含你提到的ticker工具的用法:


方法一:手动同步轴范围比例

直接调整其中一个轴的上下限,让它和另一个轴的范围成比例,就能保证零点对齐:

import numpy as np
import matplotlib.pyplot as plt

# 你的原有绘图代码
fig2 = plt.figure(constrained_layout=True)
gs = fig2.add_gridspec(2, 1)
a30 = fig2.add_subplot(gs[1, 0])
a30.plot(f[0:150], c[0:150], color='blue')

a31 = a30.twinx()
a31.plot(abs(f)[0:150], p_h[0:150], color='red')

# 获取两个轴的当前范围
y1_min, y1_max = a30.get_ylim()
y2_min, y2_max = a31.get_ylim()

# 计算比例,以第一个轴为基准调整第二个轴范围
range_ratio = (y1_max - y1_min) / (y2_max - y2_min)
new_y2_min = -y1_min / range_ratio
new_y2_max = y1_max / range_ratio

# 应用新范围
a31.set_ylim(new_y2_min, new_y2_max)

plt.show()

方法二:结合LinearLocator优化刻度显示

如果你想用matplotlib.ticker工具让刻度更规整,可以搭配LinearLocator使用,同时保证零点对齐:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import LinearLocator

# 原有绘图代码
fig2 = plt.figure(constrained_layout=True)
gs = fig2.add_gridspec(2, 1)
a30 = fig2.add_subplot(gs[1, 0])
a30.plot(f[0:150], c[0:150], color='blue')
# 给第一个轴设置均匀分布的刻度
a30.yaxis.set_major_locator(LinearLocator(numticks=5))

a31 = a30.twinx()
a31.plot(abs(f)[0:150], p_h[0:150], color='red')

# 同步零点对齐的核心步骤
y1_min, y1_max = a30.get_ylim()
y2_min, y2_max = a31.get_ylim()
range_ratio = (y1_max - y1_min) / (y2_max - y2_min)
new_y2_min = -y1_min / range_ratio
new_y2_max = y1_max / range_ratio
a31.set_ylim(new_y2_min, new_y2_max)

# 给第二个轴设置相同数量的均匀刻度
a31.yaxis.set_major_locator(LinearLocator(numticks=5))

plt.show()

补充说明

你之前单独用a30.set_yticks(np.linspace(0, 1, 5))没效果,是因为只修改了刻度位置,没有调整轴的整体上下限比例。零点的垂直位置由轴的上下限相对0点的比例决定,必须同步调整范围才能对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:50:46