我想将 matplotlib 图保存为宽高比为 1.25 的 png 文件。我通过Figsize参数指定了这个比率。但是当我使用选项保存图形时bbox_inches = "tight"
那么输出 png 的大小为 553 到 396 像素,比率为 1.39。我想保留bbox_inches = "tight"
选项以防止图形边框中出现不必要的空白。我尝试了 stackoverflow 上类似帖子中建议的不同方法,但无法找到解决方案。
这是示例代码:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize = (3, 2.4), dpi = 150)
ax = plt.subplot(111)
for i in range(3):
ax.plot(np.random.random(10), np.random.random(10), "o", label = i)
ax.legend(bbox_to_anchor=(1, 0.6), title = "Title")
plt.ylabel("Label")
plt.xlabel("Label")
plt.title("Title", loc = "left")
plt.savefig("test.png", format = "png", dpi = 150, bbox_inches = "tight")
This is the output png
![enter image description here](https://i.stack.imgur.com/oHcZb.png)
The bbox_inches = "tight"
明确告诉 matplotlib 裁剪或扩展图形;因此,图形尺寸的任何设置都将丢失。因此,如果您想控制图形大小,则不能使用此选项。
您还有其他选择:
定义BBox
-
定义你自己的bbox_inches
,它确实具有所需的方面。尺寸Bbox http://matplotlib.org/devel/transformations.html#matplotlib.transforms.Bbox将会[[x0,y0],[x1,y1]]
.
import matplotlib.transforms
bbox = matplotlib.transforms.Bbox([[-0.2, -0.36], [3.45, 2.56]])
plt.savefig("test.png", format = "png", dpi = 150,bbox_inches =bbox)
![enter image description here](https://i.stack.imgur.com/SiZsr.png)
This image is now 547 x 438 pixels, thus having an aspect of 1.2488, which is as close as you can get to 1.25.
调整内边距
-
使用原始图形尺寸(3, 2.4)
并调整填充,使所有元素都适合图形。这将使用fig.subplots_adjust()
.
fig = plt.figure(figsize = (3, 2.4), dpi = 150)
fig.subplots_adjust(top=0.89,
bottom=0.195,
left=0.21,
right=0.76)
![enter image description here](https://i.stack.imgur.com/rSCGy.png)
This image now has the expected size of (3, 2.4)*150 = 450 x 360
pixels.
要自动确定子图参数,另请参阅这个问题:创建具有精确尺寸且无填充的图形(以及轴外的图例) https://stackoverflow.com/questions/42994338/creating-figure-with-exact-size-and-no-padding-and-legend-outside-the-axes
一般来说,我建议阅读这个答案 https://stackoverflow.com/a/43439132/4124317到“如何将传说从情节中剔除”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)