4

I want to create two subplots in Python (using Anaconda 2.7) but code which I wrote generates two graphs, both not showing too much. Here's the code:

import pandas as pd
import pandas.io.data as web

import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')

import datetime

start = datetime.datetime(2000, 10, 23)
end = datetime.datetime(2016, 10, 23)

df = web.DataReader("BAC", "yahoo", start, end)

df['100MA'] = pd.rolling_mean(df['Adj Close'], 100, min_periods=1)
df['STD'] = pd.rolling_std(df['Close'], 25, min_periods=1)

print(df.tail())

ax1 = plt.subplot(2, 1, 1)
df[['Adj Close', '100MA']].plot()
ax2 = plt.subplot(2, 1, 2, sharex=ax1)
df['STD'].plot()
plt.show()

Thanks in advance!

1 Answer 1

8
import pandas as pd
import pandas.io.data as web

import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')

import datetime

start = datetime.datetime(2000, 10, 23)
end = datetime.datetime(2016, 10, 23)

df = web.DataReader("BAC", "yahoo", start, end)

df['100MA'] = pd.rolling_mean(df['Adj Close'], 100, min_periods=1)
df['STD'] = pd.rolling_std(df['Close'], 25, min_periods=1)

print(df.tail())
f,axarr = plt.subplots(2,1)
df[['Adj Close', '100MA']].plot(ax=axarr[0])
df['STD'].plot(ax=axarr[1])
plt.show()

result:

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot for the answer!
@StanislavJirák no problem, If the answer addresses your question accept it by clicking on the checkmark of that answer (like here) so that others notice it will work in the first look.
I was waiting until I can accept the aswer due to the time limit (5m).
I think it's better to switch to pandas_datareader module as pandas.io.data is deprecated and doesn't work with Pandas 0.19.0. So use import pandas_datareader.data as web instead of import pandas.io.data as web. PS +1 for the great answer

Your Answer

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