2016-02-19 86 views
0

我有一個數據集,其中包含一個項目的顏色,日期和顏色選擇的數量。我將其存儲到數據幀這樣的:按熊貓指數繪圖

   date | picks |   
     ------------+-------| 
colour 
orange 2016-01-01 |  6 | 
      2016-01-01 |  4 | 
      2016-01-01 | 16 | 
black  2016-01-01 |  0 | 
      2016-01-02 |  7 | 
      2016-01-02 |  0 | 
green 2016-01-02 |  8 | 
      2016-01-02 |  5 | 
      2016-01-03 |  4 | 

df = pd.DataFrame(
    {'colour': ['orange', 'orange', 'orange', 'black', 'black', 'black', 'green', 
       'green', 'green'], 
    'date': ['2016-01-01', '2016-01-01', '2016-01-01', '2016-01-01', '2016-01-02', 
       '2016-01-02', '2016-01-02', '2016-01-02', '2016-01-03'], 
    'picks': [6, 4, 16, 0, 7, 0, 8, 5, 4]}) 
df['date'] = pd.to_datetime(df['date']) 
df = df.set_index('colour') 

我想繪製副區(相對於拾取日期),用於每種顏色,即副區由索引。有沒有辦法做到這一點?

這是我到目前爲止已經試過:

fig, axes=plt.subplot(1,3) 
for subp in axes: 
    df.plot(ax=sub,subplot=True) 

但是,這是否顯示錯誤。 我也試過這樣:

df.plot(ax=[axes[0,0],axes[0,1],axes[0,2],subplot=True) 

這一個工作,但是我想知道我怎麼可以遍歷並做到這一點,而不是簡單地將參數。

+0

你可以告訴你試過嗎? – IanS

+0

我已經更新了迄今已嘗試的工作。 – CoderBC

+0

你可以顯示你第一次嘗試的錯誤信息嗎? – IanS

回答

1

您可以使用df.groupby(level=0)將數據框向上拆分索引值。您可以遍歷此groupby對象,並將每個組繪製在單獨的子圖上。

例如:

import pandas a pd 
import matplotlib.pyplot as plt 

# This should reproduce your dataframe. 
# For simplicity, I replaced the dates with an integer to represent the day. 
# That should be easy for you to change back. 
df = pd.DataFrame([[1,6],[1,4],[1,16],[1,0],[2,7],[2,0],[2,8],[2,5],[3,4]], 
        index=['orange','orange','orange','black','black','black','green','green','green'], 
        columns=['date','picks']) 

fig,axes = plt.subplots(1,3) 

for a,(i,group) in enumerate(df.groupby(level=0)): 
    print group 
    gp = group.plot(ax=axes[a],x='date',y='picks') 
    gp.set_title(i) 

它打印:

 date picks 
black  1  0 
black  2  7 
black  2  0 
     date picks 
green  2  8 
green  2  5 
green  3  4 
     date picks 
orange  1  6 
orange  1  4 
orange  1  16 

和劇情是這樣的:

enter image description here

0

更新:剛纔看到你沒有一個Multiindex系列bu一個數據幀。在這種情況下,我的回答看起來很像tom's

colors = df.index.unique() 
f, axarr = plt.subplots(len(colors)) 
for idx, color in enumerate(colors): 
    df.groupby(df.index).get_group(color).plot(ax=axarr[idx], x='date', y='picks') 

原件以下答案。


這項工作?

首先,我創建了一些數據:

iterables = [['orange', 'black', 'green'], [1, 2, 3, 4, 5]] 
index = pd.MultiIndex.from_product(iterables, names=['color', 'date']) 
s = pd.Series(np.random.randn(15), index=index) 

然後我繪製它:

colors = s.index.levels[0].tolist() 
f, axarr = plt.subplots(len(colors), sharex=True) 
for idx, color in enumerate(colors): 
    s[color].plot(ax=axarr[idx])