我想将 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")
最佳答案
bbox_inches = "tight"
明确告诉 matplotlib 裁剪或扩展图形;因此,图形尺寸的任何设置都将丢失。因此,如果您想控制图形大小,则不能使用此选项。
您还有其他选择:
定义BBox
定义您自己的
bbox_inches
,它确实具有所需的方面。 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)
调整内边距
使用原始图形大小
(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)
要自动确定子图参数,另请参阅此问题:Creating figure with exact size and no padding (and legend outside the axes)
总的来说,我建议阅读 this answer到“如何将图例从情节中删除”。
关于python - 以预定义的宽度/高度比保存右侧带有图例的 matplotlib 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47083648/