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

Matplotlib中twinx双Y轴的范围调整与轴线分离方法问询

Matplotlib双轴图表的两个问题解决方法

一、调整每个Y轴的范围

直接给对应的轴对象调用set_ylim(min_value, max_value)方法即可,分别设置主Y轴(ax1)和副Y轴(ax2)的上下限。比如根据你的数据,主Y轴可以设为5到16,副Y轴设为100到250,既能完整展示数据,也能留出适当余量。

二、实现两条Y轴线分离

默认twinx()创建的副Y轴和主Y轴是重叠的,要分开它们,需要调整副Y轴的轴脊(spine)位置:

  • 用ax2.spines['right'].set_position(('axes', 1.08))把副Y轴向右偏移(1.08表示相对于轴宽度的108%位置)
  • 再用ax2.yaxis.set_label_coords(1.12, 0.5)调整副Y轴标签的位置,避免被轴挡住

修改后的完整代码

import matplotlib.pyplot as plt

# Data for the x-axis
x = [1, 2, 3, 4, 5]

# Data for the primary y-axis
y1 = [10, 15, 7, 12, 9]

# Data for the secondary y-axis
y2 = [200, 150, 120, 180, 220]

# Create figure and axes objects
fig, ax1 = plt.subplots(figsize=(14,5))

# Plot the data for the primary y-axis
ax1.plot(x, y1, 'g-', label='Primary')
ax1.set_xlabel('X-axis')
ax1.set_ylabel('Primary Y-axis')
ax1.tick_params('y', colors='black')

# 调整主Y轴范围
ax1.set_ylim(5, 16)

# Create a second axes that shares the same x-axis
ax2 = ax1.twinx()

# 分离两条Y轴线
ax2.spines['right'].set_position(('axes', 1.08))  # 向右偏移副Y轴
ax2.yaxis.set_label_coords(1.12, 0.5)  # 调整副Y轴标签位置

# Plot the data for the secondary y-axis
ax2.plot(x, y2, 'b-', label='Secondary')
ax2.set_ylabel('Secondary Y-axis')
ax2.tick_params('y', colors='black')

# 调整副Y轴范围
ax2.set_ylim(100, 250)

# Add a legend
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc='upper right')

# Set the title and display the chart
plt.title('Dual Axis Line Chart')
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:32:48