alec_djinn alec_djinn - 5 months ago 50
Python Question

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

Consider the following code running in iPython 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 got the two series merged in one single plot.
Why is that? How can I get two separate plots keeping the for loop?

Answer

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 *
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()
Comments