我在使用 Matplotlib Gridspec 时遇到了一个奇怪的问题。我正在制作一个带有嵌套网格的绘图,并且我想要一个紧密/受限的布局以避免刻度标签重叠:
我的想法是使用ight_layout,在我使用嵌套Gridspec 之前它工作得很好。现在,无论我如何调用它,我都会收到错误。这是复制该问题的 MWE:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gs
import numpy as np
fig = plt.figure(figsize=(15,10), constrained_layout=True)
grid = gs.GridSpec(8,5, width_ratios=[1,2,1.5,1,1], figure=fig)
a = plt.subplot(grid[0:3,0])
b = plt.subplot(grid[0:4,1])
c = plt.subplot(grid[4:,0:2])
d = plt.subplot(grid[0:2,2:])
e = plt.subplot(grid[2:4,2:])
f = plt.subplot(grid[4:6,2:])
g = plt.subplot(grid[6:,2:])
# create nested grid plot
nested_grid = gs.GridSpecFromSubplotSpec(5,5, subplot_spec=c, wspace=0, hspace=0)
c.get_xaxis().set_ticks([])
c.get_yaxis().set_ticks([])
for k in range(25):
x, y = np.unravel_index(k, (5, 5))
gax = fig.add_subplot(nested_grid[x, y])
gax.set_xticklabels('')
gax.set_yticklabels('')
gax.set_xticks([])
gax.set_yticks([])
grid.tight_layout(fig)
这里的最后一行是 Gridspec 文档中建议的内容;以前,我没有设置数字,只是使用了 plt.tight_layout()
,这会引发错误并引导我探索 Gridspec 特定的 tight_layout()
方法。但我仍然遇到同样的错误:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-14-1002aa79c5cf> in <module>
25 gax.set_yticks([])
26
---> 27 grid.tight_layout(fig)
~/miniconda3/lib/python3.8/site-packages/matplotlib/gridspec.py in tight_layout(self, figure, renderer, pad, h_pad, w_pad, rect)
412 """
413
--> 414 subplotspec_list = tight_layout.get_subplotspec_list(
415 figure.axes, grid_spec=self)
416 if None in subplotspec_list:
~/miniconda3/lib/python3.8/site-packages/matplotlib/tight_layout.py in get_subplotspec_list(axes_list, grid_spec)
247 if hasattr(axes_or_locator, "get_subplotspec"):
248 subplotspec = axes_or_locator.get_subplotspec()
--> 249 subplotspec = subplotspec.get_topmost_subplotspec()
250 gs = subplotspec.get_gridspec()
251 if grid_spec is not None:
~/miniconda3/lib/python3.8/site-packages/matplotlib/gridspec.py in get_topmost_subplotspec(self)
611 gridspec = self.get_gridspec()
612 if hasattr(gridspec, "get_topmost_subplotspec"):
--> 613 return gridspec.get_topmost_subplotspec()
614 else:
615 return self
~/miniconda3/lib/python3.8/site-packages/matplotlib/gridspec.py in get_topmost_subplotspec(self)
483 Return the topmost `.SubplotSpec` instance associated with the subplot.
484 """
--> 485 return self._subplot_spec.get_topmost_subplotspec()
486
487
AttributeError: 'AxesSubplot' object has no attribute 'get_topmost_subplotspec'
注意:我尝试将 constrained_layout()
与 plt.figure()
调用一起使用,这没有什么区别(并且当我在第一个 Gridspec 调用。)
编辑:请参阅下面的答案以获取解决方案!这是现在的样子:
最佳答案
出现此错误的问题是 gs.GridSpecFromSubplotSpec(5,5, subplot_spec=c)
中的 subplot_spec
参数类型需要为 matplotlib .gridspec.SubplotSpec
。但c
的类型是matplotlib.axes._subplots.AxesSubplot
。
将c
更改为grid[4:,0:2]
可以解决问题。
gs.GridSpecFromSubplotSpec(5, 5, subplot_spec=grid[4:,0:2])
关于python - 使用嵌套 Matplotlib Gridspec 的紧密布局时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63028779/