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

Matplotlib使用invert_xaxis()后,如何仅让次Y轴柱状图反转

解决Matplotlib中仅反转次Y轴水平柱状图的问题

问题原因

使用ax1.twinx()创建的次轴与主轴共享X轴,调用ax2.invert_xaxis()会同步修改共享的X轴属性,导致主Y轴的散点图也被反转。

解决方案

不用invert_xaxis(),改用以下两种方式实现仅反转次轴柱状图的效果:

方法1:反转次轴X轴显示范围

通过直接设置次轴的X轴范围为反向,而非修改共享轴的反转属性,不会影响主轴。

示例代码:

import matplotlib.pyplot as plt
import numpy as np

# 生成示例数据
y = np.arange(10)
scatter_x1 = np.random.rand(10) * 10
scatter_x2 = np.random.rand(10) * 10
bar_x = np.random.rand(10) * 5

# 创建画布和主轴
fig, ax1 = plt.subplots()

# 主轴绘制散点图
ax1.scatter(scatter_x1, y, color='crimson', label='散点系列1')
ax1.scatter(scatter_x2, y, color='deepskyblue', label='散点系列2')
ax1.set_ylabel('Y轴刻度')
ax1.set_xlabel('主X轴')
ax1.legend(loc='upper left')

# 创建次Y轴
ax2 = ax1.twinx()

# 次轴绘制水平柱状图
ax2.barh(y, bar_x, color='forestgreen', alpha=0.5, label='水平柱状图')
# 反转次轴X轴范围(关键代码)
ax2.set_xlim(ax2.get_xlim()[::-1])
ax2.set_ylabel('次Y轴关联刻度')
ax2.legend(loc='upper right')

plt.tight_layout()
plt.show()

方法2:反向绘制柱状图

将柱状图的宽度设为负数,让柱子向左侧延伸,再调整次轴的刻度标签为正数,视觉上实现反转效果。

示例代码:

import matplotlib.pyplot as plt
import numpy as np

# 生成示例数据
y = np.arange(10)
scatter_x1 = np.random.rand(10) * 10
scatter_x2 = np.random.rand(10) * 10
bar_x = np.random.rand(10) * 5

# 创建画布和主轴
fig, ax1 = plt.subplots()

# 主轴绘制散点图
ax1.scatter(scatter_x1, y, color='crimson', label='散点系列1')
ax1.scatter(scatter_x2, y, color='deepskyblue', label='散点系列2')
ax1.set_ylabel('Y轴刻度')
ax1.set_xlabel('主X轴')
ax1.legend(loc='upper left')

# 创建次Y轴
ax2 = ax1.twinx()

# 负宽度绘制柱状图(向左延伸)
ax2.barh(y, -bar_x, color='forestgreen', alpha=0.5, label='水平柱状图')
# 调整次轴刻度为正数,匹配实际数值
ax2.set_xticks(np.arange(0, 6))
ax2.set_xticklabels(np.arange(5, -1, -1))
ax2.set_ylabel('次Y轴关联刻度')
ax2.legend(loc='upper right')

plt.tight_layout()
plt.show()

说明

两种方法都避免了修改共享X轴的反转属性,确保主轴散点图不受影响,同时实现次轴柱状图的反转需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:55:04