似乎在 v2 中,matplotlib 进行了更改,以减少它在跨越大范围的对数轴上绘制的刻度/标签的数量。下面的代码显示了添加回刻度的一种方法。
有了这段代码,
import pylab as plt
import numpy as np
from matplotlib.ticker import LogLocator
plt.rc('text', usetex=True)
f,ax=plt.subplots(figsize=(10,8))
plt.xscale('log')
plt.yscale('log')
plt.ylim([1e26,1e29])
plt.xlim([20,1e10])
plt.xlabel(r'x',fontsize=22)
plt.ylabel(r'y',fontsize=22)
plt.tick_params(axis='both', which='major', labelsize=22,length=9,direction='in')
plt.tick_params(axis='both', which='minor', labelsize=22,length=5,direction='in')
ax.yaxis.set_tick_params(right='on',which='both')
ax.xaxis.set_tick_params(top='on',which='both')
# manipulate x-axis ticks and labels
ax.xaxis.set_major_locator(LogLocator(numticks=15)) #(1)
ax.xaxis.set_minor_locator(LogLocator(numticks=15,subs=np.arange(2,10))) #(2)
for label in ax.xaxis.get_ticklabels()[::2]:
label.set_visible(False) #(3)
plt.savefig('example.pdf',bbox_inches='tight')
我每十年获得一次主要刻度,在主要刻度之间获得 8 个次要刻度,以及每隔一个主要刻度的轴标签。但由于我刚刚注册了一个帐户来发布此答案,因此我没有足够的声誉来分享相应的图像:(。
每个标记行的一些详细信息(请参阅上面代码中的编号注释):
- 增加允许的刻度线的最大数量。值 15 是 v1 的阈值,请参阅源代码
matplotlib/lib/matplotlib/ticker.py
.
- 当绘图轴跨越超过 5 个十年(未记录,但请参阅源代码)时,matplotlib v2 默认仅在 (2,4,6,8) 处绘制小刻度。这指定了小刻度的完整范围。
- 关闭所有其他 x 轴标签,请参阅例如这个答案 https://stackoverflow.com/a/20341184.