Home > Enterprise >  Is it possible to get GridSpec from Figure before adding Axes?
Is it possible to get GridSpec from Figure before adding Axes?

Time:11-24

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?

CodePudding user response:

This is the code defining the add_gridspec method:

    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 is a list of gridspecs, e.g.,

>>> 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)]
>>>
  • Related