josepmaria
josepmaria

Reputation: 571

Saved matplotlib size on pdf is larger than original figure

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?

Upvotes: 1

Views: 195

Answers (2)

josepmaria
josepmaria

Reputation: 571

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

plt.gcf().set_size_inches(6, 4)

Upvotes: 1

Liris
Liris

Reputation: 1511

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)

Upvotes: 1

Related Questions