2016-01-08 55 views
4

通常我總是會在這裏得到我的問題的答案,所以這裏是一個新的問題。我正在進行一些數據分析,在其中導入不同的csv文件,設置索引,然後嘗試繪製它。Pandas Python共享x軸

這是代碼。請注意,我用obdobje-obdobje因爲索引來自不同的文件,但格式是一樣的:

#to start plotting 
fig, axes = plt.subplots(nrows=2, ncols=1) 

#first dataframe 
df1_D1[obdobje:].plot(ax=axes[0], linewidth=2, color='b', linestyle='solid') 

#second dataframe 
df2_D1[obdobje:].plot(ax=axes[0], linewidth=2, color='b',linestyle='dashed') 

#third data frame 
df_index[:-obdobje].plot(ax=axes[1]) 

plt.show() 

這裏是在數據幀導入數據:

  Adj Close 
Date     
2015-12-01 73912.6016 
2015-11-02 75638.3984 
2015-10-01 79409.0000 
2015-09-01 74205.5000 
2015-08-03 75210.3984 

      Location  CLI 
TIME       
1957-12-01  GBR 98.06755 
1958-01-01  GBR 98.09290 
1958-02-01  GBR 98.16694 
1958-03-01  GBR 98.27734 
1958-04-01  GBR 98.40984 

和輸出我得到的是: enter image description here

所以,問題是,X軸不共享。他們很接近,但不共享。任何建議如何解決這個問題?我嘗試了sharex=True,但每次Python崩潰。

在此先感謝你們。

最好的問候,大衛

回答

2

您可能需要重新索引你的最後數據幀的所有數據幀的聯合。 matplotlib在啓用sharex=True時,將最後一個子圖的x軸作爲整個繪圖的軸。這應該讓你前進,

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 

fig, axes = plt.subplots(nrows=2, 
         ncols=1, 
         sharex=True) 

df1 = pd.DataFrame(
    data = np.random.rand(25, 1), 
    index=pd.date_range('2015-05-05', periods=25), 
    columns=['DF1'] 
) 

df2 = pd.DataFrame(
    data = np.random.rand(25, 1), 
    index=pd.date_range('2015-04-10', periods=25), 
    columns=['DF2'] 
) 

df3 = pd.DataFrame(
    data = np.random.rand(50, 1), 
    index=pd.date_range('2015-03-20', periods=50), 
    columns=['DF3'] 
) 

df3 = df3.reindex(index=df3.index.union(df2.index).union(df1.index)) 

df1.plot(ax=axes[0], linewidth=2, color='b', linestyle='solid') 
df2.plot(ax=axes[0], linewidth=2, color='b', linestyle='dashed') 
df3.plot(ax=axes[1]) 

plt.show() 

生成此, enter image description here

正如你所看到的,軸對準現在。

+0

謝謝,現在它工作。但我有一個新問題。在哪裏設置具體的日期或更有用,如何設置時間來繪圖?假設我只想觀察最近6個月,12個月? – DavidV

+0

@DavidV你可以通過簡單地這樣做(在我上面的例子中):'df3 [-30:]。plot(ax = axes [1])''。那隻會繪製過去的三十天。 –

+0

:)再次感謝.. :)工作,因爲它應該。我還嘗試用日常數據更改一個數據框(首先我使用每月數據),並且所有事情都發生了變化。我怎樣才能以每月數據繪製一個數據框,以及如何以上述相同的方式繪製日常數據?我知道那段簡單的解決方案將無法工作;)但是我也知道我沒有得到連接結果,因爲我應該這樣做。建議? – DavidV