Last active
November 30, 2016 21:22
-
-
Save soply/620fcee86439c875189d95ef26004ae1 to your computer and use it in GitHub Desktop.
Conveniently plot multiple plots in a single figure with matplotlib.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def show_1dplots(plots, cols = 1, titles = None, xvals = None): | |
"""Display a list of plots in a single figure with matplotlib. | |
Parameters | |
--------- | |
plots: List of np.arrays compatible with plt.plot. | |
cols (Default = 1): Number of columns in figure (number of rows is | |
set to np.ceil(n_plots/float(cols))). | |
titles: List of titles corresponding to each plot. Must have | |
the same length as titles. | |
xvals: List of xaxis that shall be used for the given plots. Either | |
no xaxis is given, ie. xvals is None, or we are given an | |
xaxis for all plots. | |
""" | |
assert((titles is None) or (len(plots) == len(titles))) | |
assert((xvals is None) or (len(plots) == len(xvals))) | |
n_plots = len(plots) | |
if titles is None: titles = ['Plot (%d)' % i for i in range(1,n_plots + 1)] | |
fig = plt.figure() | |
for n, (single_plot, title) in enumerate(zip(plots, titles)): | |
a = fig.add_subplot(cols, np.ceil(n_plots/float(cols)), n + 1) | |
if xvals is not None: | |
plt.plot(xvals[n], single_plot) | |
else: | |
plt.plot(single_plot) | |
a.set_title(title) | |
fig.set_size_inches(np.array(fig.get_size_inches()) * n_plots) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment