隐藏内部刻度线并在matplotlib子图上选择外部刻度标签?

时间:2013-10-03 13:59:27

标签: python matplotlib

我有一个由6个形状的子图组成的图形(2,3)。我想删除所有内部刻度线,只有左侧和底侧显示刻度标签。

默认刻度线:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(2,3,
                       sharex = True,
                       sharey = True)
plt.subplots_adjust(hspace = 0,
                    wspace = 0)

产生这个:

Default

看了无数的例子后,我设法删除了内部刻度线,但现在又出现了新的(额外的)刻度标签。我找到的用于删除刻度标签的解决方案不起作用,它们会删除所有x(或y)刻度标签,而不仅仅是指定的轴。

新代码:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(2,3,
                       sharex = True,
                       sharey = True)
plt.subplots_adjust(hspace = 0,
                    wspace = 0)
ax[0,0].xaxis.set_ticks_position('top')
ax[0,0].yaxis.set_ticks_position('left')
ax[0,1].xaxis.set_ticks_position('top')
ax[0,1].yaxis.set_ticks_position('none')
ax[0,2].xaxis.set_ticks_position('top')
ax[0,2].yaxis.set_ticks_position('right')

ax[1,0].xaxis.set_ticks_position('bottom')
ax[1,0].yaxis.set_ticks_position('left')
ax[1,1].xaxis.set_ticks_position('bottom')
ax[1,1].yaxis.set_ticks_position('none')
ax[1,2].xaxis.set_ticks_position('bottom')
ax[1,2].yaxis.set_ticks_position('right')

产生这个:

Attempt

我想要的最终输出是:

Final

请注意左侧和底部的标签,但周边有刻度标记。

2 个答案:

答案 0 :(得分:4)

这适用于任意大小的网格。你的问题是你没有删除蜱,你只是将它们移到顶部:

import matplotlib.pyplot as plt
import numpy as np

Nrows = 2
Ncols = 3

fig, ax = plt.subplots(Nrows, Ncols,
                       sharex=True,
                       sharey=True)
plt.subplots_adjust(hspace=0,
                    wspace=0)


for i in range(Nrows):
    for j in range(Ncols):
        if i == 0:
            ax[i,j].xaxis.set_ticks_position('top')
            plt.setp(ax[i,j].get_xticklabels(), visible=False)
        elif i == Nrows-1:
            ax[i,j].xaxis.set_ticks_position('bottom')
        else:
            ax[i,j].xaxis.set_ticks_position('none')

        if j == 0:
            ax[i,j].yaxis.set_ticks_position('left')
        elif j == Ncols-1:
            ax[i,j].yaxis.set_ticks_position('right')
            plt.setp(ax[i,j].get_yticklabels(), visible=False)
        else:
            ax[i,j].yaxis.set_ticks_position('none')

答案 1 :(得分:0)

下面的功能删除内轴刻度标签:

import matplotlib.pyplot as plt
import numpy as np

def remove_internal_ticks(ax,remove_x = True,remove_y = True):
    '''Function removes ytick labels from all the subplots (ax) other than those on
    the first column (provided remove_y=True) and all xtick labels from subplots (ax) 
    other than those on the bottom row (provided remove_x=True).'''
    nrows = np.size(ax,0)
    ncols = np.size(ax,1)
    for i in range(nrows):
        for j in range(ncols):
            if remove_x and i<nrows-1:
                plt.setp(ax[i,j].get_xticklabels(), visible=False)

            if remove_y and j>0:
                plt.setp(ax[i,j].get_yticklabels(), visible=False)