iPython/Jupyter Notebook and Pandas, how to plot multiple graphs in a for loop?

Question:

Consider the following code running in iPython/Jupyter Notebook:

from pandas import *
%matplotlib inline

ys = [[0,1,2,3,4],[4,3,2,1,0]]
x_ax = [0,1,2,3,4]

for y_ax in ys:
    ts = Series(y_ax,index=x_ax)
    ts.plot(kind='bar', figsize=(15,5))

I would expect to have 2 separate plots as output, instead, I get the two series merged in one single plot.
Why is that? How can I get two separate plots keeping the for loop?

Asked By: alec_djinn

||

Answers:

Just add the call to plt.show() after you plot the graph (you might want to import matplotlib.pyplot to do that), like this:

from pandas import Series
import matplotlib.pyplot as plt
%matplotlib inline

ys = [[0,1,2,3,4],[4,3,2,1,0]]
x_ax = [0,1,2,3,4]

for y_ax in ys:
    ts = Series(y_ax,index=x_ax)
    ts.plot(kind='bar', figsize=(15,5))
    plt.show()
Answered By: Andrey Sobolev

In the IPython notebook the best way to do this is often with subplots. You create multiple axes on the same figure and then render the figure in the notebook. For example:

import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline

ys = [[0,1,2,3,4],[4,3,2,1,0]]
x_ax = [0,1,2,3,4]

fig, axs = plt.subplots(ncols=2, figsize=(10, 4))
for i, y_ax in enumerate(ys):
    pd.Series(y_ax, index=x_ax).plot(kind='bar', ax=axs[i])
    axs[i].set_title('Plot number {}'.format(i+1))

generates the following charts

enter image description here

Answered By: jmz