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

Question:

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?

Asked By: Barzi2001

||

Answers:

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)]
>>>
Answered By: gboffi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.