熊猫绘制多个类别行

时间:2017-10-12 19:21:41

标签: pandas matplotlib

说我有以下数据......

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轴上的日期 - 我该怎么做?

2 个答案:

答案 0 :(得分:3)

您可以使用groupby和plot

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

答案 1 :(得分: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