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

如何在Matplotlib图表的顶部和右侧轴添加对数刻度及副刻度?

解决Matplotlib对数图顶部/右侧副刻度显示问题

你的代码里ax.tick_params(top=True, right=True)仅启用了主刻度的显示,要让顶部和右侧轴同步显示副刻度,只需补充which='both'参数,覆盖主、副刻度的配置规则即可。

修改后的完整代码

import numpy as np
import matplotlib.pyplot as plt

x  = np.logspace(2, 5, 5)
y  = 0.5*x**(-1/2)
y2 = 0.01*x**(-1/2)
y3 = 0.05*x**(-1/3)

fig, ax = plt.subplots()

ax.plot(x, y, 'o-', label="One")
ax.plot(x, y2, '*-', label="Two")
ax.plot(x, y3, '--', label="Three")

ax.set(
    xlabel='Input',
    xlim=(1e2, 1e5),
    xscale='log',
    ylabel='Output',
    ylim=(1e-5, 1e-1), 
    yscale='log',   
)

# 同时启用顶部、右侧轴的主/副刻度显示
ax.tick_params(top=True, right=True, which='both')

ax.legend(loc='lower left');
plt.show()

关键说明

  • which='both'参数指定对**主刻度(major)和副刻度(minor)**都应用显示配置,解决了原代码仅生效主刻度的问题。
  • 由于你已经设置了xscale='log'和yscale='log',Matplotlib会自动生成对数刻度对应的副刻度,无需额外手动定义刻度位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 03:40:35