1

I just read an introduction to subplot2grid http://matplotlib.org/users/gridspec.html

I don't understand why it is used like

fig = plt.figure()
plt.subplot2grid((2,2),(0, 0))

rather than

fig = plt.figure()
fig.subplot2grid((2,2),(0, 0))

By plt.subplot2grid(...), if I have created multiple figures, which figure the subplot is on?

updogliu
  • 6,066
  • 7
  • 37
  • 50

2 Answers2

1

plt.* functions act on the current figure. To get the current figure you can do

fig = plt.gcf()

So, in your second case you can do:

# Add subplots to the current figure
plt.subplot2grid((2, 2), (0, 0))

# Get the current figure. This will hold the subplots created in the previous command
fig = plt.gcf()

Hope this helps.

dmcdougall
  • 2,456
  • 1
  • 17
  • 15
  • So if I want to do it on a particular figure, I need to set it as the current figure first? – updogliu Oct 27 '12 at 09:52
  • Exactly. To keep track of your figures, you can assign them numbers like so: `fig1 = plt.figure(1)` or `fig2 = plt.figure(2)`. You can then switch the current figure back to `fig1` like so: `plt.figure(1)`. Hope that helps. – dmcdougall Oct 27 '12 at 17:10
  • [This](http://stackoverflow.com/questions/7986567/matplotlib-how-to-set-the-current-figure) explains it better. – dmcdougall Oct 27 '12 at 17:11
1

There are two model for interacting with matplotlib, the state machine interface (plt.*) and the OOP model (acting on figure or axes, etc). The state machine interface imitates matlab and is very useful for interactive sessions to quickly, however if you are going to do anything problematically it is much better to use the OOP interface. Mixing the two can lead to problems.

Community
  • 1
  • 1
tacaswell
  • 84,579
  • 22
  • 210
  • 199
  • 2
    You leave it completely unclear how you would use `subplot2grid` in OOP model, since `Figure` has no `subplot2grid` attribute. Therefore this answer is not at all helpful. – ImportanceOfBeingErnest Nov 26 '16 at 20:01
  • 2
    Indeed. I'm searching for the OOP version of subplot2grid. Does anyone knoes it? I found http://stackoverflow.com/questions/28256144/matplotlib-what-is-the-oop-equivalent-of-gridspec-or-plt-subplot2grid, but it is also not calling fig methods. – Michael Hooreman Feb 03 '17 at 08:05