2016-10-25 53 views
4

我想在Python中創建兩個子圖(使用Anaconda 2.7),但是我編寫的代碼會生成兩個圖,兩者都不會顯示太多。 代碼如下:Python中的兩個子圖(matplotlib)

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

在此先感謝!

回答

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

結果:

enter image description here

+0

非常感謝您的回答! –

+0

@StanislavJirák沒問題,如果答案解決了您的問題,請點擊該答案的複選標記([like here](http://i.stack.imgur.com/QpogP.png)),以便其他人注意它將在第一眼看到。 – Yugi

+1

由於時間限制(5分鐘),我一直在等待,直到我可以接受下載。 –