Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting Multiple Lines in iPython/pandas Produces Multiple Plots

I am trying to get my head around matplotlib's state machine model, but I am running into an error when trying to plot multiple lines on a single plot. From what I understand, the following code should produce a single plot with two lines:

import pandas as pd
import pandas.io.data as web
aapl = web.get_data_yahoo('AAPL', '1/1/2005')

# extract adjusted close
adj_close = aapl.loc[:, ['Adj Close']]

# 2 lines on one plot
hold(False)
adj_close.resample('M', how='min').plot()
adj_close.resample('M', how='max').plot()

In fact, I get three figures: first a blank one, and then two with one line each.

blank plotfirst plotsecond plot

Any idea what I am doing wrong or what setting on my system might be misconfigured?

like image 851
BringMyCakeBack Avatar asked Jan 28 '15 22:01

BringMyCakeBack


1 Answers

You can pre-create an axis object using matplotlibs pyplot package and then append the plots to this axis object:

import pandas as pd
import pandas.io.data as web
import matplotlib.pyplot as plt

aapl = web.get_data_yahoo('AAPL', '1/1/2005')

# extract adjusted close
adj_close = aapl.loc[:, ['Adj Close']]

# 2 lines on one plot
#hold(False)

fig, ax = plt.subplots(1, 1)
adj_close.resample('M', how='min').plot(ax=ax)
adj_close.resample('M', how='max').plot(ax=ax)

Plot example

Alternatively, you could concat the two series into a m x 2 DataFrame and plot the dataframe instead:

s1 = adj_close.resample('M', how='min')
s2 = adj_close.resample('M', how='max')
df = pd.concat([s1, s2], axis=1)
df.plot()
like image 173
cstotzer Avatar answered Nov 03 '22 04:11

cstotzer