Search code examples
pythonmatplotlibsavepngfigure

Save figures to have the same size independet of x ticks, ylabels


I am trying to create some figures for publication. When I insert them into latex they don't line up well. Essentially because the x ticks and labels are different they end up looking like this:

enter image description here

The code am using to save those figures is the following:

size_f = 20
#### Set labels ####
ax.set_ylabel(r'$W_{kin} \ [eV]$', fontsize=size_f)
ax.set_xlabel(r'$Time \  [sec]$', fontsize=size_f)


#### Set fig dimensions ####
plt.rcParams["figure.figsize"] = [10,8]

#### Set tick size ####
ax.tick_params(axis='x',labelsize=size_f)
ax.tick_params(axis='y',labelsize=size_f)


#### Save figure ####
fig.savefig(r'C:\Users\nikos.000\vlahos\png\Dw_UCS.png', format='png',dpi=300,bbox_inches='tight')

How could I make the boxes have the same size so the figures line up better, independently of the axis ticks and labels.


Solution

  • I strongly recommend you to use matplotlib.pyplot.subplots. You can adjust features of each subplot without disordering general appearance. I add code for you to use your project.

    import matplotlib.pyplot as plt
    
    x = range(10)
    y = range(10)
    
    size_f = 12
    
    labels = ("(a)", "(b)", "(c)", "(d)")
    
    fig, ax = plt.subplots(2, 2, figsize=(10, 8))
    ax[0, 0].plot(x, y, 'r')
    ax[0, 0].text(-0.1, 1., labels[0], transform=ax[0, 0].transAxes, fontsize=15, fontweight='normal', va='top', ha='right')
    ax[0, 1].plot(x, y, 'b') 
    ax[0, 1].text(-0.1, 1., labels[1], transform=ax[0, 1].transAxes, fontsize=15, fontweight='normal', va='top', ha='right')
    ax[1, 0].plot(x, y, 'g') 
    ax[1, 0].text(-0.1, 1., labels[2], transform=ax[1, 0].transAxes, fontsize=15, fontweight='normal', va='top', ha='right')
    ax[1, 1].plot(x, y, 'k') 
    ax[1, 1].text(-0.1, 1., labels[3], transform=ax[1, 1].transAxes, fontsize=15, fontweight='normal', va='top', ha='right')
    
    for row in range(2):
        for col in range(2):
            ax[row, col].set_ylabel(r'$W_{kin} \ [eV]$', fontsize=size_f)
            ax[row, col].set_xlabel(r'$Time \  [sec]$', fontsize=size_f)
    
    fig.subplots_adjust(wspace=0.3)
    fig.subplots_adjust(hspace=0.3) 
    fig.savefig(r'C:\Users\nikos.000\vlahos\png\Dw_UCS.png', format='png',dpi=300,bbox_inches='tight')
    

    The figure: enter image description here

    Since you will have common and independent features for each subplot, I didn't put everything into for-blocks.