1

When checking matplotlib figure size is :

fig_width, fig_height = plt.gcf().get_size_inches()
print(fig_width, fig_height)

6.0 4.0 ´<Figure size 3600x2400 with 0 Axes>´

One of the params to create the figure was:

plt.rcParams["figure.dpi"] = 600

I save the figure with the following code:

plt.savefig("figure.pdf", format= 'pdf', bbox_inches="tight",dpi=600)

When checking resulting pdf size I can see it is larger than the original one:

enter image description here

I also tried saving the image without specifying dpi, but result was the same:

plt.savefig("figure.pdf", format= 'pdf', bbox_inches="tight")

I read this page, but could not find the answer.

How should I save the matploblig figure so that resulting pdf is desired size 6*4 inches and 600 dpi resolution?

josepmaria
  • 373
  • 1
  • 11

2 Answers2

1

Do not use bbox_inches="tight", which try to remove the white border but changes the fig size while doing so.

Instead, create your figure using layout = 'constrained' or layout = 'tight':

fig = plt.figure(layout='constrained') 
plt.savefig("figure.pdf", dpi=600)
Liris
  • 1,399
  • 3
  • 11
  • 29
  • when entering the first line of your code, i get the error TypeError: __init__() got an unexpected keyword argument 'layout' – josepmaria Jul 20 '23 at 12:26
  • 1
    @josepmaria What version of Matplotlib are you using? – jared Jul 20 '23 at 16:49
  • 1
    @josepmaria Update `matplotlib` to the last version, or use `constrained_layout=True` instead of `layout=constrained`. – Liris Jul 21 '23 at 13:03
  • @jared current matplotlib version is 3.4.3 – josepmaria Jul 24 '23 at 07:39
  • 1
    @josepmaria It looks like the `layout` argument was added around version 3.6. If you're going to stick to 3.4, use `constrained_layout=True`, as @Liris suggested. – jared Jul 24 '23 at 07:55
1

Adding the following line before plt.savefig() solved the issue:

plt.gcf().set_size_inches(6, 4)
josepmaria
  • 373
  • 1
  • 11