如何对齐Matplotlib中主次X轴的刻度?
解决主次X轴刻度对齐问题
问题根源在于twiny()创建的次轴默认会独立计算自身X范围,导致其刻度位置与主轴无法一一对应。要实现absolute_mags和masses的精准对齐,只需强制次轴的X范围与主轴完全一致,并确保刻度位置匹配。
修改后的代码
import numpy as np import matplotlib.pyplot as plt # 生成模拟数据(匹配题目给出的高斯分布参数) np.random.seed(42) absolute_RP_mags = np.random.normal(loc=9.86406767115786, scale=1.7088087089866282, size=1000) absolute_mags = np.array([4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14.5]) masses = 10 ** (np.array([0.058, -0.039, -0.136, -0.233, -0.333, -0.463, -0.637, -0.778, -0.867, -0.964, -1.11])) masses = np.around(masses, 2) plt.hist(absolute_RP_mags, bins='auto', linewidth=2, hatch='/', edgecolor='k', facecolor='None') plt.ylabel("number of targets") plt.xlabel("absolute G_RP magnitude (mag)") ax1 = plt.gca() ax1.set_xticks(ticks=absolute_mags, labels=absolute_mags) ax2 = ax1.twiny() # 核心调整:强制次轴X范围与主轴完全一致 ax2.set_xlim(ax1.get_xlim()) ax2.set_xticks(ticks=absolute_mags, labels=masses) ax2.set_xlabel("mass ($M/M_\odot$)") plt.show()
额外需求:将次轴移至底部与主轴同侧
如果需要把次轴从顶部移到底部(避免顶部偏移),可添加以下代码调整布局:
# 将次轴刻度移至底部 ax2.xaxis.set_ticks_position('bottom') # 向下偏移次轴轴线,避免与主轴重叠 ax2.spines['bottom'].set_position(('outward', 30)) # 调整次轴标签到主标签下方 ax2.xaxis.set_label_coords(0.5, -0.2)
添加后,次轴会显示在主X轴下方,刻度与主轴完全对齐。
内容的提问来源于stack exchange,提问作者Rin
相关产品推荐
相关产品推荐

