matplotlib宽范围对数X轴无法显示次网格线问题咨询
问题原因
- 当log坐标轴的数量级跨度≥6时,matplotlib默认会将主刻度步长调整为2个数量级,避免刻度过度拥挤,同时默认隐藏了区间内的次刻度
- 代码中注释使用的
AutoMinorLocator是线性轴专属的次刻度定位器,不适用于log轴场景,无法生效
解决代码
import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import MultipleLocator, AutoMinorLocator, LogLocator freqs = np.logspace(2,4) freqs_ext = np.logspace(2, 10) fig, ax = plt.subplots(1,2, figsize=(12,4)) ax[0].plot(freqs , freqs**2) ax[0].grid(which='both') ax[0].set_xscale( 'log') ax[1].plot(freqs_ext,freqs_ext**2) # 强制x轴主刻度每1个数量级显示 ax[1].xaxis.set_major_locator(LogLocator(base=10, subs=(1.0,))) # 设置x轴次刻度为每个数量级下1-9的系数刻度 ax[1].xaxis.set_minor_locator(LogLocator(base=10, subs=np.arange(1,10, dtype=float))) ax[1].grid(which='both') ax[1].set_xscale('log') plt.show()
补充说明
如果希望次网格线显示更清晰,可以额外配置网格样式:
ax[1].grid(which='minor', linestyle=':', linewidth=0.5, color='gray')
运行上述代码后,右侧子图会和左侧子图一致显示完整的X轴次网格线。
内容的提问来源于stack exchange,提问作者Michele Ancis
相关产品推荐
相关产品推荐

