2017-10-12 103 views
2

說我有以下數據...大熊貓情節多類別行

date  Score category     
2017-01-01 50.0   1 
2017-01-01 590.0   2 
2017-01-02 30.0   1 
2017-01-02 210.4   2 
2017-01-03 11.0   1 
2017-01-03 50.3   2 

所以每天的基礎上,我有多個類別,每個類別被分配一個分數。 這裏是我到目前爲止的代碼...

vals = [{'date': '2017-01-01', 'category': 1, 'Score': 50}, 
     {'date': '2017-01-01', 'category': 2, 'Score': 590}, 
     {'date': '2017-01-02', 'category': 1, 'Score': 30}, 
     {'date': '2017-01-02', 'category': 2, 'Score': 210.4}, 
     {'date': '2017-01-03', 'category': 1, 'Score': 11}, 
     {'date': '2017-01-03', 'category': 2, 'Score': 50.3}] 
df = pd.DataFrame(vals) 
df.date = pd.to_datetime(df['date'], format='%Y-%m-%d') 
df.set_index(['date'],inplace=True) 

導致如下一個離奇的情節。 enter image description here

我想要有多條線,每個類別一個,並在X軸上的日期 - 我將如何做到這一點?

回答

3

您可以使用GROUPBY和情節

fig, ax = plt.subplots() 
for label, grp in df.groupby('category'): 
    grp.plot(x = grp.index, y = 'Score',ax = ax, label = label) 

enter image description here

+0

PERFECTO,謝謝! – Craig

2

讓我們嘗試用軸與ax=ax和參數secondary_y=True

ax = df.plot(x=df.index, y='Score') 
df.plot(x=df.index, y='category', secondary_y=True, ax=ax) 

輸出:

enter image description here

或者,如果@Vaishali情節是你想要的,你可以用這一行代碼來完成。

df.set_index('category',append=True).unstack()['Score'].plot() 

輸出:

enter image description here

+0

你確實愛set_index(),stack,unstack!:) – Vaishali

+0

@Vaishali。謝謝! –