Skip to content Skip to sidebar Skip to footer

IPython/Jupyter Notebook And Pandas, How To Plot Multiple Graphs In A For Loop?

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

Solution 1:

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

Solution 2:

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


Post a Comment for "IPython/Jupyter Notebook And Pandas, How To Plot Multiple Graphs In A For Loop?"