如何在Pandas中创建groupby子图?

elk*_*000 4 python matplotlib pandas seaborn

我有一个带有犯罪时间序列数据的数据框,其中有一个攻击方面(看起来像下面的格式).我想对数据框进行分组绘图,以便随着时间的推移探索犯罪趋势.

    Offence                     Rolling year total number of offences       Month
0   Criminal damage and arson   1001                                        2003-03-31
1   Drug offences               66                                         2003-03-31
2   All other theft offences    617                                   2003-03-31
3   Bicycle theft               92                                    2003-03-31
4   Domestic burglary           282                                   2003-03-31
Run Code Online (Sandbox Code Playgroud)

我有一些代码可以完成这项工作,但它有点笨拙并且它丢失了Pandas在单个绘图上提供的时间序列格式.(我已经包含了一张图片来说明).任何人都可以建议我可以使用这种情节的成语吗?

我会转向Seaborn,但我无法弄清楚如何将xlabel格式化为时间序列.

[![subs = \[\]
for idx, (i, g) in enumerate(df.groupby("Offence")):
        subs.append({"data": g.set_index("Month").resample("QS-APR", how="sum" ).ix\["2010":\],
                     "title":i})

ax = plt.figure(figsize=(25,15))
for i,g in enumerate(subs):
    plt.subplot(5, 5, i)
    plt.plot(g\['data'\])
    plt.title(g\['title'\])
    plt.xlabel("Time")
    plt.ylabel("No. of crimes")
    plt.tight_layout()][1]][1]
Run Code Online (Sandbox Code Playgroud)

Ser*_*nov 11

这是Pandas中6个散点图的可重现的例子,pd.groupby()连续6年获得.在x轴上 - 年份有油价(布伦特原油),y为同年的sp500值.

import matplotlib.pyplot as plt
import pandas as pd
import Quandl as ql
%matplotlib inline

brent = ql.get('FRED/DCOILBRENTEU')
sp500 = ql.get('YAHOO/INDEX_GSPC')
values = pd.DataFrame({'brent':brent.VALUE, 'sp500':sp500.Close}).dropna()["2009":"2015"]

fig, axes = plt.subplots(2,3, figsize=(15,5))
for (year, group), ax in zip(values.groupby(values.index.year), axes.flatten()):
    group.plot(x='brent', y='sp500', kind='scatter', ax=ax, title=year)
Run Code Online (Sandbox Code Playgroud)

这产生了以下情节:

在此输入图像描述

(以防万一,从这些图中你可以推断,2010年石油与sp500之间存在很强的相关性,而其他年份却没有.)

您可以更改kindgroup.plot()使其适合您的特定种类或数据.我的预期,如果你的数据中有pandas,它将保留x轴的日期格式.