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?
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.
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 .).
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With