Search code examples
pythonmatplotlibseabornsubplot

Matpltlib/Seaborn remove empty axis and also move shared-x tick labels


I'm plotting a selection of graphs using matplotlib and seaborn. When I remove the empty axes, the tick labels do not move to the graphs above them - is there a way to do this?

fig, ax = plt.subplots(9,4,figsize=(20, 30), sharey=True, sharex=True)
for r in range(0,9):
   for c in range(0,4):
    
       if (r==8) and (c>=2):
           pass
       else:
           data_red = preds[preds['region']==regions[(r*4)+c]]
           sns.scatterplot(data=data_red, x='y_test', y='preds', ax=ax[r,c], alpha=0.6, legend=False)
           ax[r,c].plot(sl,sl, 'r-')
           ax[r,c].set_xlabel('')
           ax[r,c].set_ylabel('')
           ax[r,c].tick_params(axis='both', which='major', labelsize=20)
           ax[r,c].annotate(regions[(r*4)+c], (550,200), fontsize=15)
           ax[r,c].annotate(f'RMSE: {rmse_regs[(r*4)+c]}', (550,150), fontsize=15)
           ax[r,c].annotate(f'Bias: {bias_regs[(r*4)+c]}', (550,100), fontsize=15)      
        
        
        
fig.delaxes(ax[8,2])
fig.delaxes(ax[8,3])
fig.text(0.5, -0.02, 'x', fontsize=25, ha='center')
fig.text(-0.02, 0.5, 'y', fontsize=25, va='center', rotation='vertical')
plt.tight_layout()
plt.show()

Example of what's happening here

What I want to happen


Solution

  • Since there is no data presented, I created a graph using the data set in seaborn. I used this answer as a reference for how to add the x-axis tick marks due to the deletion of the graph.

    import seaborn as sns
    import matplotlib.pyplot as plt
    import numpy as np
    
    tips = sns.load_dataset("tips")
    
    fig, axs = plt.subplots(9,4,figsize=(10, 15), sharey=True, sharex=True)
    
    for ax in axs.ravel():
        sns.scatterplot(data=tips, x="total_bill", y="tip", ax=ax, alpha=0.6, legend=False)
        ax.set(xlabel='', ylabel='')
        ax.plot(np.arange(tips['total_bill'].min(),tips['total_bill'].max(),10),
                np.arange(tips['tip'].min(),tips['tip'].max(),2),'r--')
    
    fig.delaxes(axs[8,2])
    fig.delaxes(axs[8,3])
    # add xticks
    axs[7,2].xaxis.set_tick_params(which='both', labelbottom=True, labeltop=False)
    axs[7,3].xaxis.set_tick_params(which='both', labelbottom=True, labeltop=False)
    
    fig.text(0.5, -0.02, 'x', fontsize=25, ha='center')
    fig.text(-0.02, 0.5, 'y', fontsize=25, va='center', rotation='vertical')
    plt.tight_layout()
    plt.show()
    

    enter image description here