3

I am trying to add subplots of differing sizes to a particular matplotlib figure, and am unsure of how to do so. In the case of there only being one figure, the "subplot2grid" can be utilized as follows:

import matplotlib.pyplot as plt

fig = plt.figure()

ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2)
ax1 = plt.subplot2grid((2, 2), (1, 1))

plt.show()

The above code creates a figure, and adds two subplots to that figure, each with different dimensions. Now, my issue arises in the case of having multiple figures -- I cannot find the appropriate way to add subplots to a particular figure using "subplot2grid." Using the more simple "add_subplot" method, one can add subplots to a particular figure, as seen in the below code:

import matplotlib.pyplot as plt

fig1 = plt.figure()
fig2 = plt.figure()

ax1 = fig1.add_subplot(2, 2, 1)
ax2 = fig1.add_subplot(2, 2, 4)

plt.show()

I am looking for the analogous method for adding subplots of different sizes (preferably using some sort of grid manager, e.g. "subplot2grid") to a particular figure. I have reservations about using the plt."x" style because it operates on the last figure that was created -- my code will have several figures, all of which I will need to have subplots of different sizes.

Thanks in advance,

Curtis M.

Curtis Mason
  • 45
  • 1
  • 4
  • 1
    You can set the current figure, then your plt."x" style command will go to whichever figure you have chosen. https://stackoverflow.com/questions/7986567/matplotlib-how-to-set-the-current-figure#7987462 – RuthC Aug 30 '17 at 20:17

1 Answers1

4

In the future (probably the upcoming release?), subplot2grid will take a fig argument

subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs)

such that the following would be possible:

import matplotlib.pyplot as plt

fig1=plt.figure()
fig2=plt.figure()

ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2, fig=fig1)
ax2 = plt.subplot2grid((2, 2), (1, 1),  fig=fig1)

plt.show()

As of now (version 2.0.2) this is not yet possible. Alternatively, you can manually define the underlying GridSpec

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig1=plt.figure()
fig2=plt.figure()

spec1 = GridSpec(2, 2).new_subplotspec((0,0), colspan=2)
ax1 = fig1.add_subplot(spec1)
spec2 = GridSpec(2, 2).new_subplotspec((1,1))
ax2 = fig1.add_subplot(spec2)

plt.show()

Or you can simply set the current figure, such that plt.subplot2grid will work on that exact figure (as shown in this question)

import matplotlib.pyplot as plt

fig1=plt.figure(1)
fig2=plt.figure(2)

# ... some other stuff

plt.figure(1) # set current figure to fig1
ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2)
ax2 = plt.subplot2grid((2, 2), (1, 1))

plt.show()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712