Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a subplot from a function

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?

like image 232
Martin Preusse Avatar asked Nov 19 '13 13:11

Martin Preusse


People also ask

What is the function subplot return?

Matplotlib - Subplots() Function The function returns a figure object and a tuple containing axes objects equal to nrows*ncols. Each axes object is accessible by its index.

How do you return subplots in Python?

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 .).

What does the Pyplot method subplots return?

pyplot. subplots method provides a way to plot multiple plots on a single figure. Given the number of rows and columns , it returns a tuple ( fig , ax ), giving a single figure fig with an array of axes ax .

How do I return a figure from a function in matplotlib?

MatPlotLib with Python Make a function plot(x, y) that creates a new figure or activate an existing figure using figure() method. Plot the x and y data points using plot() method; return fig instance. Call plot(x, y) method and store the figure instance in a variable, f. To display the figure, use show() method.


1 Answers

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.

like image 137
Joe Kington Avatar answered Oct 09 '22 13:10

Joe Kington