如何按类别绘制一段时间

时间:2017-05-07 13:54:20

标签: python pandas matplotlib

我有两个列,分类和年份,我试图绘制。我试图获取每年每个分类的总和来创建一个多级时间序列图。

ax = data[data.categorical=="cat1"]["categorical"].plot(label='cat1')
data[data.categorical=="cat2"]["categorical"].plot(ax=ax, label='cat3')
data[data.categorical=="cat3"]["categorical"].plot(ax=ax, label='cat3')
plt.xlabel("Year")
plt.ylabel("Number per category")
sns.despine()

但是我得到一个错误,说明没有数字数据要绘制。我正在寻找与上述类似的东西,可能是data[data.categorical=="cat3"]["categorical"].lambda x : (1 for x in data.categorical)

我将使用以下列表作为示例。

categorical = ["cat1","cat1","cat2","cat3","cat2","cat1","cat3","cat2","cat1","cat3","cat3","cat3","cat2","cat1","cat2","cat3","cat2","cat2","cat3","cat1","cat1","cat1","cat3"]

year = [2013,2014,2013,2015,2014,2014,2013,2014,2014,2015,2015,2013,2014,2014,2013,2014,2015,2015,2015,2013,2014,2015,2013]

我的目标是获得类似下图的内容 enter image description here

2 个答案:

答案 0 :(得分:3)

我不愿意将此称为“解决方案”,因为它基本上只是基本Pandas功能的摘要,在您找到时间序列的同一文档中对此进行了解释情节你已经放在你的帖子里了。但是看到groupby和绘图之间存在一些混淆,一个演示可能有助于澄清问题。

我们可以使用两次groupby()来电 第一个groupby()使用count聚合获得每年类别出现次数 第二个groupby()用于绘制每个类别的时间序列。

首先,生成一个示例数据框:

import pandas as pd
categorical = ["cat1","cat1","cat2","cat3","cat2","cat1","cat3","cat2",
               "cat1","cat3","cat3","cat3","cat2","cat1","cat2","cat3",
               "cat2","cat2","cat3","cat1","cat1","cat1","cat3"]
year = [2013,2014,2013,2015,2014,2014,2013,2014,2014,2015,2015,2013,
        2014,2014,2013,2014,2015,2015,2015,2013,2014,2015,2013]
df = pd.DataFrame({'categorical':categorical,
                   'year':year})

   categorical  year
 0        cat1  2013
 1        cat1  2014
                 ...
21        cat1  2015
22        cat3  2013

现在每年按类别计算:

# reset_index() gives a column for counting, after groupby uses year and category
ctdf = (df.reset_index()
          .groupby(['year','categorical'], as_index=False)
          .count()
          # rename isn't strictly necessary here, it's just for readability
          .rename(columns={'index':'ct'})
       )

   year categorical  ct
0  2013        cat1   2
1  2013        cat2   2
2  2013        cat3   3
3  2014        cat1   5
4  2014        cat2   3
5  2014        cat3   1
6  2015        cat1   1
7  2015        cat2   2
8  2015        cat3   4

最后,绘制每个类别的时间序列,按颜色键入:

from matplotlib import pyplot as plt
fig, ax = plt.subplots()

# key gives the group name (i.e. category), data gives the actual values
for key, data in ctdf.groupby('categorical'):
    data.plot(x='year', y='ct', ax=ax, label=key)

time series plot by category

答案 1 :(得分:0)

你尝试过groupby吗?

df.groupby(["year","categorical"]).count()