matplotlib

时间:2016-01-22 11:00:24

标签: python matplotlib plot subplot

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

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

这是我目前使用的代码,用于自定义刻度:

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,我不能这样做,并且在底部子图中指定方向为“out”会破坏中间的刻度线。由于子图之间没有空格,底部图的顶部与中间子图的底部共享其x轴等...

有解决方法吗?

enter image description here

1 个答案:

答案 0 :(得分:1)

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

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()