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

Matplotlib多Y轴刻度重叠不可读问题求助

解决Matplotlib双右侧Y轴刻度重叠问题

问题场景

使用Matplotlib绘制柱状图+双折线图组合图时,右侧两个Y轴的刻度完全重叠,无法正常读取。需求为:左Y轴(Rate)范围0-16,右侧两个Y轴(ChangeRate_1、ChangeRate_2)范围均为-50到180。

修改后的完整代码

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.cm import get_cmap
from matplotlib.ticker import FormatStrFormatter

# 数据准备
data = {
    'Year': ['2010','2011','2012','2013','2014','2015','2016','2017','2018','2019'],
    'Rate':[10,10,9,7,5,5,5,5,5,5],
    'ChangeRate_1':[7,-50,24,150,8,10,60,5,180,5],
    'ChangeRate_2':[7,6,-3,1,8,5,8,5,15,5],
}

df = pd.DataFrame(data, columns = ['Year', 'Rate', 'ChangeRate_1', 'ChangeRate_2'])

# 绘制组合图
fig, ax_1 = plt.subplots(figsize = (10, 5))  # 加宽画布,给右侧轴留出空间
ax_2 = ax_1.twinx()
ax_3 = ax_2.twinx()  

cmap = get_cmap('tab10')

# 绘制各元素
ax_1.bar(df['Year'], df['Rate'], label = 'Rate', color = cmap(0))
ax_2.plot(df['Year'], df['ChangeRate_1'], label = 'ChangeRate_1', color = cmap(0.1), linewidth = 3.5)
ax_3.plot(df['Year'], df['ChangeRate_2'], label = 'ChangeRate_2', color = cmap(0.2), linewidth = 3.5)

# 获取图例元素
handles_1, labels_1 = ax_1.get_legend_handles_labels()
handles_2, labels_2 = ax_2.get_legend_handles_labels()
handles_3, labels_3 = ax_3.get_legend_handles_labels()

# 设置轴范围
ax_1.set_ylim(0, 16)
ax_2.set_ylim(-50, 180)
ax_3.set_ylim(-50, 180)  # 统一右侧两个轴的范围

# 调整第三个轴的位置,避免与第二个轴重叠
ax_3.spines['right'].set_position(('axes', 1.2))

# 修正图例(原代码错误地将labels_3加入handles列表)
ax_1.legend(handles = handles_1 + handles_2 + handles_3, 
            labels = labels_1 + labels_2 + labels_3, 
            loc = 'upper right', 
            shadow = True)

ax_1.grid(axis = 'y')
ax_1.set_title('Comparison of revenues', fontsize=11)

# 设置轴标签,调整第三个轴标签位置避免遮挡
ax_1.set_ylabel('Rate')
ax_2.set_ylabel('ChangeRate_1')
ax_3.set_ylabel('ChangeRate_2', labelpad=20)

ax_1.xaxis.set_major_formatter(FormatStrFormatter('%.0f'))
plt.savefig('ComparisonOfRevenues.pdf', bbox_inches='tight')  # 保存时包含所有元素
plt.show()

关键修改说明

  • 偏移右侧轴位置:通过ax_3.spines['right'].set_position(('axes', 1.2))将第三个Y轴向右偏移,和第二个右侧轴拉开距离,彻底解决刻度重叠问题。
  • 修正图例错误:原代码中handles = handles_1 + handles_2 + labels_3是逻辑错误,替换为handles_1 + handles_2 + handles_3后图例可正常显示所有元素。
  • 统一右侧轴范围:给ax_3添加set_ylim(-50, 180),保证两个右侧轴的刻度范围一致。
  • 优化画布与保存:加宽画布尺寸,保存时使用bbox_inches='tight'确保所有轴标签、图例都被完整保存,不会被截断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:20:31