matplotlibseaborn

Why don't matplotlib savefig dimensions match figsize dimensions?


I'm trying to make a figure of an exact size for a publication.

fig,axn = plt.subplots(2,2, figsize=(8,8))

x = [2,4,6,8]
y = [10,3,20,4]

sns.scatterplot(x=x, y=y, ax=axn[0,0])


plt.savefig(r"filepath\test.png"
           )

This gives me a png file measuring 5in x 5in with lots of white space around the edges

enter image description here

if I use the following savefig call:

fig,axn = plt.subplots(2,2, figsize=(8,8))

x = [2,4,6,8]
y = [10,3,20,4]

sns.scatterplot(x=x, y=y, ax=axn[0,0])


plt.savefig(r"filepath\test.png",
            bbox_inches="tight"
           )

I get an image that has no whitespace but now measures 6.7in x 6.4in

enter image description here

All the posts I've found on this topic suggest that adding "bbox_inches="tight"" would remove the whitespace and preserve the figsize dimensions but this doesn't appear to work for me.

Is it a case of adjusting (guessing) what the figsize dimensions need to be to give the right absolute image size once the whitespace has been removed?

Thanks in advance


Solution

  • Instead of tight_layout using bbox_inches="tight", I would suggest either of the following ways for better control:

    The easy but less flexible option is to use constrained layout. Check out the guide here.

    fig, axn = plt.subplots(2, 2, figsize=(8,8), layout='constrained')
    x = [2,4,6,8]
    y = [10,3,20,4]
    sns.scatterplot(x=x, y=y, ax=axn[0,0])
    fig.savefig(r"filepath\test.pdf")
    

    Better yet is to specify spacing manually using subplots_adjust before saving. Read the documentation to understand how the values work.

    fig, axn = plt.subplots(2, 2, figsize=(8,8))
    x = [2,4,6,8]
    y = [10,3,20,4]
    sns.scatterplot(x=x, y=y, ax=axn[0,0])
    fig.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95,
                        wspace=0.1, hspace=0.1)
    fig.savefig(r"filepath\test.pdf")
    

    You might also want to save the images in a vector format like SVG or PDF for high quality images.