17

Using Matplotlib in an IPython Notebook, I would like to create a figure with subplots which are returned from a function:

import matplotlib.pyplot as plt

%matplotlib inline

def create_subplot(data):
    more_data = do_something_on_data()  
    bp = plt.boxplot(more_data)
    # return boxplot?
    return bp

# make figure with subplots
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(10,5))

ax1 -> how can I get the plot from create_subplot() and put it on ax1?
ax1 -> how can I get the plot from create_subplot() and put it on ax2?

I know that I can directly add a plot to an axis:

ax1.boxplot(data)

But how can I return a plot from a function and use it as a subplot?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Martin Preusse
  • 9,151
  • 12
  • 48
  • 80

1 Answers1

28

Typically, you'd do something like this:

def create_subplot(data, ax=None):
    if ax is None:
        ax = plt.gca()
    more_data = do_something_on_data()  
    bp = ax.boxplot(more_data)
    return bp

# make figure with subplots
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(10,5))
create_subplot(data, ax1)

You don't "return a plot from a function and use it as a subplot". Instead you need to plot the boxplot on the axes in the subplot.

The if ax is None portion is just there so that passing in an explicit axes is optional (if not, the current pyplot axes will be used, identical to calling plt.boxplot.). If you'd prefer, you can leave it out and require that a specific axes be specified.

Joe Kington
  • 275,208
  • 71
  • 604
  • 463
  • 3
    Great, that works! The 'nature' of the figure and axes objects and the logic behind the plotting commands can be difficult to understand at the beginning. – Martin Preusse Nov 19 '13 at 14:07
  • "Instead you need to plot the boxplot on the axes in the subplot." This is what I needed to make my mental shift. Thanks – Mitchell van Zuylen Jul 01 '18 at 14:45