【问题标题】:Matplotlib/Pyplot shared axis for odd number of subplotsMatplotlib/Pyplot 共享轴用于奇数个子图
【发布时间】:2015-07-21 22:45:39
【问题描述】:

我正在使用以下代码生成我希望 '对接' 在一起并共享轴的奇数个图。

import matplotlib.pyplot as plt

fig = plt.figure()

ax1 = fig.add_subplot(4,2,1)
ax1.set_yscale('log')
ax1.set_xscale('log')
plt.subplot(4,2,2, sharex=ax1, sharey=ax1)
plt.subplot(4,2,3, sharex=ax1, sharey=ax1)
plt.subplot(4,2,4, sharex=ax1, sharey=ax1)
plt.subplot(4,2,5, sharex=ax1, sharey=ax1)
plt.subplot(4,2,6, sharex=ax1, sharey=ax1)
plt.subplot(4,2,7, sharex=ax1, sharey=ax1)

plt.suptitle('The main title')
plt.xlabel('Some Value')
plt.ylabel("Value")


for ax in plt.gcf().axes:                           #To suppress Tick labels in subsequent subplots and keep only the left and bottom ones.
    print ax
    try:
        ax.label_outer()
    except:       
        pass

plt.subplots_adjust(wspace=0, hspace=0)

plt.show()

经过多次搜索发现,使用pyplot.gcf().axes,只能获取外部标签,使得标签不重复。

这正是我想要的,并且在图像数量为偶数时效果很好。

但是,当我有奇数个子图(例如,定义了 4x2 但只有 7 个子图)时,如示例所示,我希望 x 轴抽动也出现在右下图的 x 轴上不仅在左侧子图上。

很遗憾,我是新手,不允许发布图片。希望我的描述很清楚。如果你能想象出一张与link上的类似的图片

【问题讨论】:

    标签: python matplotlib axis-labels subplot


    【解决方案1】:

    您可以根据它们在图中的位置手动打开和关闭 x 和 y 刻度标签。这个demo 有更多信息。

    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    
    # Add subplots
    nRows = 4
    nCols = 2
    nPlots = 7
    ax1 = fig.add_subplot(nRows,nCols,1)
    ax1.set_yscale('log')
    ax1.set_xscale('log')
    
    for n in range(1, nPlots+1):
        plt.subplot(nRows,nCols,n, sharex=ax1, sharey=ax1)
    
    # Turn off tick lables where needed. 
    index = 0
    for r in range(1, nRows +1):
         for c in range(1, nCols + 1):
             index += 1
             # Turn off y tick labels for all but the first column.
             if ((c != 1) and (index <= nPlots)):  
                 ax = plt.subplot(nRows, nCols, index, sharex=ax1, sharey=ax1)
                 plt.setp(ax.get_yticklabels(), visible=False)
              # Turn off x tick lables for all but the bottom plot in each 
              # column. 
             if ((nPlots - index) >= nCols):
                 ax = plt.subplot(nRows, nCols, index, sharex=ax1, sharey=ax1) 
                 plt.setp(ax.get_xticklabels(), visible=False)
    
    plt.subplots_adjust(wspace=0, hspace=0)
    
    plt.show()
    

    【讨论】:

    • 优秀的解决方案。正是我想要的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-05-27
    • 2014-05-01
    • 1970-01-01
    • 2016-10-10
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多