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

如何控制Matplotlib顶部轴刻度?自定义刻度未显示问题解决

问题分析与解决方案

原代码存在的问题

  1. 导入语句语法错误:import numpy as np import matplotlib.pyplot as plt 需拆分为两行独立导入
  2. 顶部轴刻度位置xticks0中的值大多小于底部轴的xmin=3,超出显示范围导致刻度无法显示
  3. 用户指定的底部特定值中,多数对应位置不在3~15的底部轴范围内,无法生成可见的顶部刻度

方案一:严格遵循底部轴3~15范围

只显示该范围内对应的顶部刻度:

import numpy as np
import matplotlib.pyplot as plt

c = 3.1
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

# 底部轴范围内的特定值,对应顶部刻度标签为3.1/该值
bottom_specific_vals = [3, 3.1, 6.2, 15]
xvals = np.arange(3, 16, 0.0001)
data = xvals
ax1.plot(xvals, data)

# 设置顶部轴刻度位置为底部轴特定值
ax2.set_xticks(bottom_specific_vals)
# 同步顶部轴范围与底部轴一致
ax2.set_xbound(ax1.get_xbound())
# 生成顶部轴刻度标签
ax2.set_xticklabels(["%.2f" % (c/x) for x in bottom_specific_vals])

ax1.set_xlabel("harmonic order")
ax2.set_xlabel('Wavelength (micrometer)')
ax1.grid(True)
plt.xlim(xmin=3, xmax=15)
plt.tick_params(labelsize=12)

plt.show()

方案二:调整底部轴范围以显示所有指定顶部刻度

若希望显示用户指定的全部顶部刻度值(3、2.5、2、1.5、1、0.5、0.2),需将底部轴范围调整为1~15.5:

import numpy as np
import matplotlib.pyplot as plt

c = 3.1
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

# 用户目标顶部刻度值
top_tick_vals = [3, 2.5, 2, 1.5, 1, 0.5, 0.2]
# 计算对应的底部轴位置:x = 3.1 / 顶部刻度值
bottom_tick_positions = [c / val for val in top_tick_vals]

xvals = np.arange(1, 15.6, 0.0001)
data = xvals
ax1.plot(xvals, data)

# 设置顶部轴刻度位置为计算出的底部轴位置
ax2.set_xticks(bottom_tick_positions)
ax2.set_xbound(ax1.get_xbound())
# 使用用户指定的顶部刻度值作为标签
ax2.set_xticklabels(["%.2f" % val for val in top_tick_vals])

ax1.set_xlabel("harmonic order")
ax2.set_xlabel('Wavelength (micrometer)')
ax1.grid(True)
plt.xlim(xmin=1, xmax=15.5)
plt.tick_params(labelsize=12)

plt.show()

内容的提问来源于stack exchange,提问作者김재일

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:22:37