pandas 绘制多个类别线 [英] Pandas plot multiple category lines
本文介绍了 pandas 绘制多个类别线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有以下数据...
Say I have the following data...
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
因此,我每天都有多个类别,每个类别都有一个分数.到目前为止,这是我的代码...
So on a daily basis, I have multiple categories, each being assigned a score. Here's my code so far...
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)
这将导致如下所示的奇异图.
Which results in a bizarre plot as below.
我想要多行,每个类别一行,以及 X 轴上的日期 - 我该怎么做?
I'd like to have multiple lines, one for each category, and the date on the X-axis - how would I do this?
推荐答案
可以使用 groupby 和 plot
You can use groupby and plot
fig, ax = plt.subplots()
for label, grp in df.groupby('category'):
grp.plot(x = grp.index, y = 'Score',ax = ax, label = label)
这篇关于 pandas 绘制多个类别线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文