iPython/Jupyter Notebook and Pandas, how to plot multiple graphs in a for loop?
55,548
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
Author by
alec_djinn
You can PM me at alec_djinn-at-yahoo-doooot-com if you need ;) If you think I was helpful, feel free to buy me a coffee.
Updated on July 09, 2022Comments
-
alec_djinn almost 2 years
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? -
Mello about 3 yearsOk, but in this case it`s one figure with two subplots, I have done almost the same thing, but using indexed figure too (figs[i] and axs[i] inside loop) and plt.show(), but I was not able to interact with the figures.