不能在 matplotlib 中出现错误的情况下使用 tightlayout

can't use tightlayout without getting an error in matplotlib

在下面的代码中,如果我取消注释调用 tightlayout 的行,我会在 matplotlib 中崩溃。如果有任何建议,我将不胜感激。为什么会这样。

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
fig= plt.figure(figsize=(12, 7))
ax= fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
ax.stock_img()
# plt.tight_layout()
plt.show()

这是回溯:

回溯(最后一次调用): 文件“test.py”,第 6 行,位于 plt.tight_layout() 文件“C:\ProgramData\Anaconda3\envs\py38\lib\site-packages\matplotlib\cbook\deprecation.py”,第 451 行,在包装器中 return func(*args, **kwargs) 文件“C:\ProgramData\Anaconda3\envs\py38\lib\site-packages\matplotlib\pyplot.py”,第 1490 行,在 tight_layout gcf().tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) 文件“C:\ProgramData\Anaconda3\envs\py38\lib\site-packages\matplotlib\cbook\deprecation.py”,第 411 行,在包装器中 return func(*inner_args, **inner_kwargs) 文件“C:\ProgramData\Anaconda3\envs\py38\lib\site-packages\matplotlib\figure.py”,第 2613 行,在 tight_layout kwargs = get_tight_layout_figure( get_tight_layout_figure 中的文件“C:\ProgramData\Anaconda3\envs\py38\lib\site-packages\matplotlib\tight_layout.py”,第 303 行 kwargs = auto_adjust_subplotpars(无花果,渲染器, 文件“C:\ProgramData\Anaconda3\envs\py38\lib\site-packages\matplotlib\tight_layout.py”,第 84 行,在 auto_adjust_subplotpars bb += [ax.get_tightbbox(渲染器,for_layout_only=True)] 文件“C:\ProgramData\Anaconda3\envs\py38\lib\site-packages\matplotlib\axes_base.py”,第 4203 行,在 get_tightbbox bbox = a.get_tightbbox(渲染器) 文件“C:\ProgramData\Anaconda3\envs\py38\lib\site-packages\matplotlib\artist.py”,第 286 行,在 get_tightbbox 中 bbox = Bbox.intersection(bbox, clip_path.get_extents()) 文件“C:\ProgramData\Anaconda3\envs\py38\lib\site-packages\matplotlib\path.py”,第 603 行,在 get_extents return Bbox([xys.min(轴=0), xys.max(轴=0)]) 文件“C:\ProgramData\Anaconda3\envs\py38\lib\site-packages\numpy\core_methods.py”,第 43 行,在 _amin 中 return umr_minimum(a, axis, None, out, keepdims, initial, where) ValueError:零大小数组到最小化操作没有标识

我正在使用 Python 3.8.5 与 matplotlib 3.3.1 和 CartoPy 0.18.0。

我有完全相同的配置,并且能够重现您的错误。但是在寻找类似的回溯之后,我终于找到了 ,其中将 Matplotlib 从 3.3.1 升级到 3.3.2 已经解决了这个问题。

因此,如果您首先 运行 在终端中(使用 pip 或 conda)

conda upgrade matplotlib

pip install matplotlib==3.3.2

然后,确保 Matplotlib 已更新到 3.3.2 并且 运行 您的脚本:

import matplotlib.pyplot as plt
import cartopy.crs as ccrs

fig= plt.figure(figsize=(12, 7))
ax= fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
ax.stock_img()
plt.tight_layout()
plt.show()

在我的机器上 tight_layout() 有效地产生了所需的结果。