Pandas 熊猫绘制多个类别线
假设我有以下数据Pandas 熊猫绘制多个类别线,pandas,matplotlib,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 因此,每天我都有多个类别,每个类别都有一个分数。 这是我到
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)
这导致了一个奇怪的情节,如下所示。
我想要多行,每个类别一行,X轴上的日期-我该怎么做?您可以使用groupby和plot
fig, ax = plt.subplots()
for label, grp in df.groupby('category'):
grp.plot(x = grp.index, y = 'Score',ax = ax, label = label)
让我们试着使用带有
ax=ax
和参数secondary\u y=True的轴:
ax = df.plot(x=df.index, y='Score')
df.plot(x=df.index, y='category', secondary_y=True, ax=ax)
输出:
或者,如果@Vaishali plot是您想要的,您可以使用这一行
df.set_index('category',append=True).unstack()['Score'].plot()
输出:
您确实喜欢设置索引(),堆栈,取消堆栈!:)@瓦伊沙利。非常感谢。