如何在pyplot中为任意大小的子图网格共享轴标签?

时间:2014-01-25 22:36:11

标签: python matplotlib

我已经看到了一些接近解决我需要做的事情的答案,但没有什么比这更好。

我有一个函数可以根据传递给它的数组的大小生成可变数量的子图。问题是,当我尝试使用subplots()编写函数时,我似乎无法添加共享轴标签。此外,对于大量的情节,共享的x轴往往是不可读的,我不知道如何处理它。

def tilePlot(indivArray):
    names = list()
    num_rows = len(indivArray)
    num_cols = len(indivArray[0])
    for r in range(num_rows):
            for c in range(num_cols):
                    names.append(str(r)+str(c))

    f, names = plt.subplots(num_rows, num_cols, sharex='col', sharey='row')

    for r in range(num_rows):
        for c in range(num_cols):

            names[r][c].plot(indivArray[r][c].allValues)
            names[r][c].set_title(indivArray[r][c].name)


    f.subplots_adjust(hspace=.25)

    plt.setp([a.get_xticklabels() for a in f.axes[:]], visible=False)

    plt.show()

我尝试重写函数以使用add_subplot,但后来我不确定是否有可行的方法使子图共享轴。

def tilePlot2(indivArray):
    num_rows = len(indivArray)
    num_cols = len(indivArray[0])

    names = list()
    codes = list()
    counterlist = list()

    counter = 0

    for r in range(num_rows):

        names.append(list())
        codes.append(list())
        counterlist.append(list())

        for c in range(num_cols):
            counter+=1
            names[r].append(str(r)+str(c))
            codes[r].append(c)
            counterlist[r].append(counter)



    fig = plt.figure()
    ax = fig.add_subplot(111)    # The big subplot


    for r in range(num_rows):
        for c in range(num_cols):

            names[r][c]=fig.add_subplot(num_rows, num_cols, counterlist[r][c])

    # Turn off axis lines and ticks of the big subplot
    ax.spines['top'].set_color('none')
    ax.spines['bottom'].set_color('none')
    ax.spines['left'].set_color('none')
    ax.spines['right'].set_color('none')
    ax.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off')

    for r in range(num_rows):
        for c in range(num_cols):

            names[r][c].plot(indivArray[r][c].allValues)
            names[r][c].set_title(indivArray[r][c].name)

    # Set common labels
    ax.set_xlabel('Time (s)')
    ax.set_ylabel('RFU')

    fig.subplots_adjust(hspace=.25)

    plt.setp([a.get_xticklabels() for a in fig.axes[-1:]], visible=False)        
    plt.show()

我很抱歉我的代码不够优雅,我是Matplotlib的新手。谢谢!

0 个答案:

没有答案