matplotlib 是否可以在添加轴之前从图中获取GridSpec?

q35jwt9p  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(125)

Consider the following code

from matplotlib import pyplot as plt

fig = plt.figure()
grid = fig.add_gridspec(2,2)

We have that grid is a GridSpec instance.
Consider now the following code

from matplotlib import pyplot as plt

fig = plt.figure()
fig.add_gridspec(2,2)

The only way to retrieve the GridSpec associated to fig that I found is either to use the first code snippet I posted or to add a Subplot first and then get the GridSpec from such a Subplot :

axes = fig.add_subplot(grid[0])
grid = axes.get_gridspec()

But what if I want to get the GridSpec from fig directly and before adding any Subplot ?
Is it possible?

kmbjn2e3

kmbjn2e31#

下面是定义add_gridspec方法的代码:

def add_gridspec(self, nrows=1, ncols=1, **kwargs):
        """
        ...
        """
        _ = kwargs.pop('figure', None)  # pop in case user has added this...
        gs = GridSpec(nrows=nrows, ncols=ncols, figure=self, **kwargs)
        self._gridspecs.append(gs)
        return gs

Figure._gridspecs是网格规格的列表,例如,

>>> import matplotlib.pyplot as plt
... fig = plt.figure()
... fig.add_gridspec(2, 2)
... fig.add_gridspec(4, 4)
... fig._gridspecs
[GridSpec(2, 2), GridSpec(4, 4)]
>>>

相关问题