Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set absolute size of subplots

I know how to set the relative size of subplots within a figure using gridspec or subplots_adjust, and I know how to set the size of a figure using figsize. My problem is setting the absolute size of the subplots.

Use case: I am making two separate plots which will be saved as pdfs for an academic paper. One has two subplots and one has three subplots (in both cases in 1 row). I need each of the 5 subplots to be the exact same size with the exact same font sizes (axis labels, tick labels, etc) in the resulting PDFs. In the example below the fonts are the same size but the subplots are not. If I make the height of the resulting PDFs the same (and thus the axes), the font on 3-subplots.pdf is smaller than that of 2-subplots.pdf.

MWE:

import matplotlib.pyplot as plt

subplots = [2, 3]
for i, cols in enumerate(subplots):

    fig, ax = plt.subplots(1, cols, sharey=True, subplot_kw=dict(box_aspect=1))

    for j in range(cols):
        ax[j].set_title(f'plot {j*cols}')
        ax[j].set_xlabel('My x label')
    ax[0].set_ylabel('My y label')

    plt.tight_layout()
    plt.savefig(f'{cols}-subplots.pdf', bbox_inches='tight', pad_inches=0)
    plt.show()

Output: output

like image 968
nicholas Avatar asked Oct 22 '25 19:10

nicholas


1 Answers

I prefer to use fig.add_axes([left, bottom, width, height]) which let you control the size and location of each subplot precisely. left and bottom decide the location of your subplots, while width and height decide the size. All quantities are in fractions of figure width and height, thus they are all float between 0 and 1.

An example:

fig = plt.figure(figsize=(8.3, 11.7))
axs = {
    "ax1": fig.add_axes([0.2, 0.7, 0.6, 0.2], xticklabels=[]),
    "ax2": fig.add_axes([0.2, 0.49, 0.6, 0.2], xticklabels=[]),
    "ax3": fig.add_axes([0.2, 0.28, 0.6, 0.2]),
}

With this I created 3 subplots in an A4 size figure, each of them are 0.6x8.3 width and 0.2x11.7 height. The spacing between them is 0.1x11.7. "ax1" and "ax2" do not show xticklabels so that I can set shared x ticks for them later.

You can see matplotlib API refenrence for more information https://matplotlib.org/stable/api/figure_api.html

like image 74
sunflower Avatar answered Oct 24 '25 09:10

sunflower