Query regarding plt.show() function

fig = plt.figure(figsize=(12,12))
for i in range(5):
    sub_plot = fig.add_subplot(5,1,i+1)
    start_index = i*12
    end_index = (i*12) + 12
    subset = unrate[start_index : end_index]
    sub_plot.plot(subset['DATE'], subset['VALUE'])

If the plt.show() function is placed inside the for loop, the plot is plotted only for the first sub_plot. But when I place the plt.show() function outside the for loop, I am getting the correct answer (plot is plotted for 5 sub_plots). What is happening under the hood?

I don’t know exactly what’s going on under the hood, but I found this section from the Introduction to Matplotlib screen that I think explains (or at least hints at) why this is happening:

every time we call a pyplot function, the module maintains and updates the plot internally (also known as state). When we call show() , the plot is displayed and the internal state is destroyed.

I like to think of it as the plot is being built up in the background, and when all the pieces are in place (including customizing the look of the plot), we run plt.show() to display everything.