如何在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
相关产品推荐
相关产品推荐

