Saved matplotlib size on pdf is larger than original figure

huangapple go评论58阅读模式
英文:

Saved matplotlib size on pdf is larger than original figure

问题

当检查Matplotlib图形大小时:

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

结果为:
6.0 4.0
<Figure size 3600x2400 with 0 Axes>

创建图形时的一个参数是:

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

我使用以下代码保存图形:

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

检查生成的PDF文件大小时,发现它比原始大小要大:

Saved matplotlib size on pdf is larger than original figure

我还尝试了不指定dpi的方式保存图像,但结果相同:

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

我阅读了这个页面,但未找到答案。

请问我应该如何保存Matplotlib图形,以便生成的PDF文件大小为6*4英寸,分辨率为600 dpi?

英文:

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[&quot;figure.dpi&quot;] = 600

I save the figure with the following code:

plt.savefig(&quot;figure.pdf&quot;, format= &#39;pdf&#39;, bbox_inches=&quot;tight&quot;,dpi=600)

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

Saved matplotlib size on pdf is larger than original figure

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

plt.savefig(&quot;figure.pdf&quot;, format= &#39;pdf&#39;, bbox_inches=&quot;tight&quot;)

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?

答案1

得分: 1

不要使用bbox_inches="tight",它尝试去除白色边框,但在这样做时会改变图形的大小。

相反,可以使用layout = 'constrained'layout = 'tight'来创建您的图形:

fig = plt.figure(layout='constrained')
plt.savefig("figure.pdf", dpi=600)
英文:

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

Instead, create your figure using layout = &#39;constrained&#39; or layout = &#39;tight&#39;:

fig = plt.figure(layout=&#39;constrained&#39;) 
plt.savefig(&quot;figure.pdf&quot;, dpi=600)

答案2

得分: 1

plt.savefig() 之前添加以下行解决了问题:

plt.gcf().set_size_inches(6, 4)
英文:

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

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

huangapple
  • 本文由 发表于 2023年7月20日 17:43:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76728598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定