Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top