pythonmatplotlibwhitespacesubplot

How to reclaim horizontal space made available by removing labels and ticks?


I have a row of subplots which start with a histogram and the rest are some qqplots:

qqplots with extra horizontal space

I removed the y axis and ticks labels using

    for ax in axqq[1:]:
        ax.set_ylabel(None)
        ax.tick_params(labelleft=False)
        # does not help ax.yaxis.set_visible(False)
        ax.sharey(axqq[0])
    fig.tight_layout()

I would like to remove the horizontal whitespace between the QQ plots.

Since my subplots are not homogeneous (the 1st subplot is a histogram), fig.subplots_adjust does not help.


Solution

  • If I understood you correctly and you need the result as shown in the picture without using fig.subplots_adjust.

    Example result plot

    You can build your code based on the width_ratios parameter in the fig.add_gridspec() function. The code that builds the picture above.

    import matplotlib.pyplot as plt
    import numpy as np
    import scipy.stats as stats
    
    data = np.random.normal(0, 1, 1000)
    
    fig = plt.figure(figsize=(10, 4))
    gs = fig.add_gridspec(1, 7, 
                           width_ratios=[1.5, 0.5, 1, 0.00, 1, 0.00, 1], 
                           wspace=0)
    
    # First plot (hist)
    ax_hist = fig.add_subplot(gs[0])
    ax_hist.hist([1, 2, 3], bins=30, edgecolor='black')
    ax_hist.set_ylabel('Count')
    ax_hist.set_xlabel('Val')
    
    # quantiles
    axqq = [fig.add_subplot(gs[i]) for i in range(2, 7, 2)]
    stats.probplot(data, dist="norm", plot=axqq[0])
    axqq[0].set_ylabel('Y_label')
    
    for ax in axqq[1:]:
        stats.probplot(data, dist="norm", plot=ax)
        # Delete all info for Y axis
        ax.set_ylabel(None)
        ax.set_yticklabels([])
        ax.set_yticks([])
        ax.spines['left'].set_visible(False)  
        ax.get_yaxis().set_visible(False)  
    
    plt.show()