python - 以预定义的宽度/高度比保存右侧带有图例的 matplotlib 图

标签 python matplotlib

我想将 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")

这是输出png enter image description here

最佳答案

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)
    

    enter image description here
    该图像现在的尺寸为 547 x 438 像素,因此宽高比为 1.2488,最接近 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
    该图像现在的预期大小为 (3, 2.4)*150 = 450 x 360 像素。

  • 要自动确定子图参数,另请参阅此问题:Creating figure with exact size and no padding (and legend outside the axes)

总的来说,我建议阅读 this answer到“如何将图例从情节中删除”。

关于python - 以预定义的宽度/高度比保存右侧带有图例的 matplotlib 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47083648/

相关文章:

python - 安装具有量化支持的 Tensorflow

python - 在 python 中绘制没有零值的直方图?

python - 如何将 R^2 值添加到 seaborn 条形图的图例中?

python - 图GUI卡住

python - 减少绘图刻度数

python - 绘图平滑 matplotlib 和 seaborn

python - 在 Scrapy 中使用第 nth-child

python - 为什么pygame不继续循环?

python - 使用 BeautifulSoup 更改元素值返回空元素

python - 将某个字符添加到字符串后,从列表中删除该字符