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

如何旋转含twinx寄生轴的matplotlib子图X轴标签?

解决axisartist寄生轴子图X轴标签旋转无效的问题

嗨,我之前也踩过这个坑!你用的是mpl_toolkits.axisartist创建的自定义轴对象,它和matplotlib常规的Axes结构完全不同,所以普通的plt.xticks(rotation=45)根本无法作用到它的X轴标签上。不用放弃寄生轴,只要针对axisartist的轴元素直接操作就行~

具体解决步骤

  • 替换掉无效的plt.xticks(rotation = 45),直接操作host轴的底部轴标签对象
  • 可选调整标签对齐方式,避免标签显示不全

修改后的完整代码

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA

host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()

offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right", axes=par2, offset=(offset, 0))

par1.axis["right"].toggle(all=True)
par2.axis["right"].toggle(all=True)

host.set_xlim(0, 2)
host.set_ylim(0, 2)

host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")

p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")

par1.set_ylim(0, 4)
par2.set_ylim(1, 65)

host.legend()

host.axis["left"].label.set_color(p1.get_color())
par1.axis["right"].label.set_color(p2.get_color())
par2.axis["right"].label.set_color(p3.get_color())

# --- 替换原来的plt.xticks的代码 ---
host.axis["bottom"].label.set_rotation(45)
# 可选:设置水平对齐方式,让标签更美观,避免截断
host.axis["bottom"].label.set_ha('right')

plt.draw()
plt.show()

原理说明

axisartist的轴是通过axis["bottom"]、axis["left"]这种命名方式来管理各个轴组件的,标签、刻度等元素都嵌套在这些轴对象里。常规的plt.xticks是针对matplotlib原生Axes的API,无法访问到axisartist的这些自定义组件,所以必须直接操作host.axis["bottom"].label来设置旋转角度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:10:24