48

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?

2 Answers 2

72

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()
Sign up to request clarification or add additional context in comments.

3 Comments

And if one want to use the GUI (i.e. using just %matplotlib) and to scroll through the figures in that GUI (using "left/right" arrows in the GUI) - how should this be changed? Thank you
AFAIK, it's not that easy to remap GUI Back/Forward buttons to do that; however, you can add your own buttons to GUI
%matplotlib inline solved my issue. Thanks :)
31

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

1 Comment

Ok, 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.