关于python:matplotlib中的刻度线

tick marks in matplotlib

我正在使用matplotlib创建一个子图,其中顶部x轴与底部x轴不同。 我自己将xticks和xlabels添加到顶部。

我希望在中间和顶部子图的底部有与底部x轴相对应的xtick标记,其中xticks指向外部(或向下),就像在底部一样。 有没有办法做到这一点?

到目前为止,这是我用来自定义刻度的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=False, sharey=False)
f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)

ax3.get_xaxis().set_tick_params(direction='out', top='off', which='both')
ax2.get_xaxis().set_tick_params(direction='out', bottom='on', top='off', which='both')


ax1.minorticks_off()
ax1.get_xaxis().tick_top()
ax1.set_xticks([np.divide(1.0,100.0), np.divide(1.0,50.0), np.divide(1.0,35.0),
                np.divide(1.0,20.0), np.divide(1.0,10.0), np.divide(1.0,5.0),
                np.divide(1.0,3.0), np.divide(1.0,2.0), np.divide(1.0,1.0)])
ax1.set_xticklabels([100, 50, 35, 20, 10, 5, 3, 2, 1])

我发现,由于我为顶部绘图制作了自定义的xticks,因此无法执行此操作,而在底部子绘图中指定"向外"的方向会破坏中间的刻度线。 由于子图之间没有空间,因此底部图的顶部与中间子图的底部共享x轴,依此类推...

有没有解决方法?

enter image description here


您可以通过设置相应的z顺序在底部轴上方绘制中间轴。 可以通过调用axvline来完成最上面的刻度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import matplotlib.pyplot as plt
import numpy as np

f, (ax1, ax2, ax3) = plt.subplots(3, sharex=False, sharey=False)
f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)

ax3.get_xaxis().set_tick_params(direction='out', top='off', which='both')
ax2.get_xaxis().set_tick_params(direction='out', bottom='on', top='off', which='both')


ax1.minorticks_off()
ax1.get_xaxis().tick_top()
ax1.set_xticks([np.divide(1.0,100.0), np.divide(1.0,50.0), np.divide(1.0,35.0),
                np.divide(1.0,20.0), np.divide(1.0,10.0), np.divide(1.0,5.0),
                np.divide(1.0,3.0), np.divide(1.0,2.0), np.divide(1.0,1.0)])
ax1.set_xticklabels([100, 50, 35, 20, 10, 5, 3, 2, 1])

for i, ax in enumerate((ax3, ax2, ax1)):
    ax.set_zorder(i)
for tick in ax2.xaxis.get_ticklocs():
    ax2.axvline(tick, ymin=0.9)
plt.show()