Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create subplots in Matplotlib in a loop?

I am using this code which provides nice plots one after the next (using IPython-notebook & Pandas)

for subsm in subsl:
    H7, subsm = sumsubdesc2(table, subsm)   
    ax1=H7.plot()
    plt.title('Rolling 4q mean %s'%(subsm))
    ax1.set_title('Rolling 4q mean %s'%(subsm))
    ax1.set_ylim(100000,600000)

I'd like to get the plots "2up" one next to the next for 3 rows total (5 subplots) can't figure out how to handle that since all the subplot examples seem to be for subplotting ether the data or specific plots and specific grid placement.

So I don't know how to create the main plot and then subplot a number of graphs (in this case 5) with titles as two-up?

Edit line two of code since I left out the function call ;-(

like image 382
dartdog Avatar asked Jan 12 '23 08:01

dartdog


1 Answers

Here's what you need to do:

import math
import matplotlib.pylab as plt

nrows = int(math.ceil(len(subsl) / 2.))

fig, axs = plt.subplots(nrows, 2)

ylim = 100000, 600000
for ax, subsm in zip(axs.flat, subsl):
    H7, subsm = sumsubdesc2(table, subsm)
    H7.plot(ax=ax, title='Rolling 4q mean %s' % subsm)
    ax.set_ylim(ylim)

This will work even if axs.size > len(subsl) since StopIteration is raised when the shortest iterable runs out. Note that axs.flat is an iterator over the row-order flattened axs array.

To hide the last plot that isn't showing, do this:

axs.flat[-1].set_visible(False)

More generally, for axs.size - len(subsl) extra plots at the end of the grid do:

for ax in axs.flat[axs.size - 1:len(subsl) - 1:-1]:
    ax.set_visible(False)

That slice looks a little gnarly, so I'll explain:

The array axs has axs.size elements. The index of the last element of the flattened version of axs is axs.size - 1. subsl has len(subsl) elements and the same reasoning applies about the index of the last element. But, we need to move back from the last element of axs to the last plotted element so we need to step by -1.

like image 160
Phillip Cloud Avatar answered Jan 21 '23 05:01

Phillip Cloud