【问题标题】:How to create groupby subplots in Pandas?如何在 Pandas 中创建 groupby 子图?
【发布时间】:2016-01-14 00:40:09
【问题描述】:

我有一个包含犯罪时间序列数据的数据框,其中包含犯罪方面(如下所示)。我想在数据帧上执行分组图,以便可以探索一段时间内的犯罪趋势。

    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

我有一些代码可以完成这项工作,但它有点笨拙,并且失去了 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]

【问题讨论】:

  • 您对 Pandas 中按年份values.groupby(values.index.year) 连续 6 年分组的石油与黄金价格 2x3 散点图的可重复示例感兴趣吗?
  • 当然。我只是想完成这个过程......

标签: python pandas matplotlib seaborn


【解决方案1】:

这是 Pandas 中 6 个散点图的可重现示例,连续 6 年从pd.groupby() 获得。在 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)

这会产生下面的情节:

(以防万一,从这些图中您可能会推断出 2010 年石油和 sp500 之间存在很强的相关性,但其他年份则没有)。

您可以更改group.plot() 中的kind,使其适合您的特定类型或数据。我的预期是,如果您的数据中有 x 轴的日期格式,pandas 会保留它。

【讨论】:

  • 我会试一试,让你知道。看起来比我的努力简单得多。
【解决方案2】:

Altair 在这种情况下可以很好地工作。

import matplotlib.pyplot as plt
import pandas as pd
import quandl as ql

df = ql.get(["NSE/OIL.1", "WIKI/AAPL.1"], start_date="2013-1-1")
df.columns = ['OIL', 'AAPL']
df['year'] = df.index.year

from altair import *

即 #1- 按年份无颜色/按年份无列

Chart(df).mark_point(size=1).encode(x='AAPL',y='OIL').configure_cell(width=200, height=150)

Viz #2- 按年份/按年份没有颜色

Chart(df).mark_point(size=1).encode(x='AAPL',y='OIL', column='year').configure_cell(width=140, height=70).configure_facet_cell(strokeWidth=0)

Viz #3- 按年份着色

Chart(df).mark_point(size=1).encode(x='AAPL',y='OIL', color='year:N').configure_cell(width=140, height=70)

【讨论】:

    猜你喜欢
    • 2015-07-10
    • 2014-11-15
    • 2021-10-09
    • 2016-12-28
    • 1970-01-01
    • 2014-07-24
    • 2019-01-12
    • 2020-02-05
    相关资源
    最近更新 更多