gpt4 book ai didi

python - 为什么matplotlib默认不保存整图?

转载 作者:行者123 更新时间:2023-12-02 19:35:02 36 4
gpt4 key购买 nike

这可能是几乎所有使用 matplotlib 的人都会遇到的问题。如果您生成一个图 - 通常包含轴标签和图例 - 并使用默认设置保存它,您将得到一个裁剪图像。

演示代码:

import matplotlib.pyplot as plt
def plot():
plt.figure(figsize=[3,3],linewidth=5,edgecolor='r')
ax=plt.subplot()
ax.plot(range(10),range(10),label='label')
ax.set_xlabel('xlabel\nxlabel\nxlabel')
ax.set_ylabel('ylabel\nylabel\nylabel')
ax.legend(bbox_to_anchor=[1,1])
plot()
plt.savefig('no_tight_layout.png')

no_tight_layout.png

(感谢 stackoverflow),我们知道的解决方法很少,但每个都有自己的警告..
解决方法 #1: 在 matplotlib 中:使用 tight_layout 选项。

plot()    
plt.savefig('tight_layout.png',bbox_inches='tight')

tight_layout.png

它适用于简单的图形。
但是,根据我的经验,对于更复杂的多面板图形,它不是可靠的选择。tight_layout 经常会因以下错误而失败:

UserWarning: This figure includes Axes that are not compatible with tight_layout, so results might be incorrect.
UserWarning: tight_layout not applied: number of rows in subplot specifications must be multiples of one another.

解决方法 #2: 从 matplotlib 外部:将图像保存为 SVG 格式,然后转换为 png。例如,在 inkscape 命令行 UI 中使用 --export-area-drawing 选项或在 inkscape 的 GUI 中使用“resize to page”选项。

但是,在这种情况下,您必须依赖外部软件,这些软件很难作为依赖项添加到 python 包中(目前 conda 仅托管 Windows 版本的 inkscape)。

所以我的问题是..

为什么matplotlib默认不保存整图?
如果我在 jupyter notebook 中生成相同的绘图,而不使用 tight_layout 选项,我会看到绘图的所有元素都包含在图形边界内(以红色显示)。

jupyter notebook

此图是在 jupyter notebook(!) 的输出单元格中生成的。
那为什么不按原样保存呢?为什么保存的图片默认和jupyter notebook的图片不一样?
在我看来,这是 matplotlib 的一个非常基本的问题。
如果默认情况下所有元素都包含在保存的图形中而不需要任何变通方法,它不会让用户的生活更轻松吗?

最佳答案

简而言之,它是一个特性而不是 matplotlib 的一个问题。默认情况下,matplotlib 为图形设置固定大小,因此溢出的元素通常会被裁剪。

matplotlib 提供了 4 个选项来处理元素的裁剪:

  1. plt.subplots_adjust 追溯元素的手动调整。图大小不变。
  2. plt.tight_layout 自动调整。图大小不变。
  3. plt.constrained_layout 自动调整。通常类似于 fig.tight_layout。图大小不变。
  4. plt.savefig(..,bbox_inches='tight'):调整图形大小以包含所有原样的元素(您在 jupyter notebook 的输出中看到的)。图尺寸变化。

选项 4 是我所需要的,因为我想保存我在 jupyter notebook 输出中看到的图形,而不管图形大小。

我在 matplotlib's github page 上得到了这个答案(感谢 Elan Ernest @ImportanceOfBeingErnest)。

关于python - 为什么matplotlib默认不保存整图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61192115/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com