Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplot with matplotlib without knowing the number of plots before running

I have a problem with Matplotlib's subplots. I do not know the number of subplots I want to plot beforehand, but I know that I want them in two rows. so I cannot use

plt.subplot(212)

because I don't know the number that I should provide.

It should look like this:

example for plot

Right now, I plot all the plots into a folder and put them together with illustrator, but there has to be a better way with Matplotlib. I can provide my code if I was unclear somewhere.

like image 819
tarrasch Avatar asked Jun 05 '12 09:06

tarrasch


1 Answers

My understanding is that you only know the number of plots at runtime and hence are struggling with the shorthand syntax, e.g.:

plt.subplot(121)

Thankfully, to save you having to do some awkward math to figure out this number programatically, there is another interface which allows you to use the form:

plt.subplot(n_cols, n_rows, plot_num)

So in your case, given you want n plots, you can do:

n_plots = 5 # (or however many you programatically figure out you need)
n_cols = 2
n_rows = (n_plots + 1) // n_cols
for plot_num in range(n_plots):
   ax = plt.subplot(n_cols, n_rows, plot_num)
   # ... do some plotting

Alternatively, there is also a slightly more pythonic interface which you may wish to be aware of:

fig, subplots = plt.subplots(n_cols, n_rows)
for ax in subplots:
   # ... do some plotting

(Notice that this was subplots() not the plain subplot()). Although I must admit, I have never used this latter interface.

HTH

like image 92
pelson Avatar answered Oct 25 '22 01:10

pelson