如何通过子图创建 pandas 群组情节? [英] How to create Pandas groupby plot with subplots?

查看:172
本文介绍了如何通过子图创建 pandas 群组情节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数据框:

 值标识符
2007-01-01 0.781611 55
2007-01-01 0.766152 56
2007-01-01 0.766152 57
2007-02-01 0.705615 55
2007-02-01 0.032134 56
2007-02- 01 0.032134 57
2008-01-01 0.026512 55
2008-01-01 0.993124 56
2008-01-01 0.993124 57
2008-02-01 0.226420 55
2008-02-01 0.033860 56
2008-02-01 0.033860 57

所以我每个标识符做一个groupby:

  df.groupby('identifier')

现在我想在网格中生成子图,每个子图都有一个图。我尝试了两种方法:

pre $ df.groupby('identifier')。plot(subplots = True)


$或b
$ b $ $ p $ df.groupby( '标识符')。plot(subplots = False)

  plt.subplots(3,3)
df.groupby('identifier')。plot(subplots = True)

无济于事。如何创建图表?

解决方案

这是一个包含大量组(随机假数据) grouped.get_group(key)会告诉你如何做更优雅的情节。

 将pandas作为pd 
从numpy.random导入randint
导入matplotlib.pyplot作为plt


df = pd.DataFrame(randint(0,10,(200,6)),columns = list('abcdef'))
grouped = df.groupby('a ')
rowlength = grouped.ngroups / 2#修正奇数组
fig,axs = plt.subplots(figsize =(9,4),
nrows = 2,ncols = rowlength,#修正如上
gridspec_kw = dict(hspace = 0.4))#对gridspec进行大量控制

targets = zip(grouped.groups.keys(),axs.flatten() )
在枚举(目标)中为i,(key,ax):
ax.plot(grouped.get_group(key))
ax.set_title('a =%d'%key )
ax.legend()
plt.show()


I have a data frame like this:

     value     identifier
2007-01-01  0.781611      55
2007-01-01  0.766152      56
2007-01-01  0.766152      57
2007-02-01  0.705615      55
2007-02-01  0.032134      56 
2007-02-01  0.032134      57
2008-01-01  0.026512      55
2008-01-01  0.993124      56
2008-01-01  0.993124      57
2008-02-01  0.226420      55
2008-02-01  0.033860      56
2008-02-01  0.033860      57

So I do a groupby per identifier:

df.groupby('identifier')

And now I want to generate subplots in a grid, one plot per group. I tried both

df.groupby('identifier').plot(subplots=True)

or

df.groupby('identifier').plot(subplots=False)

and

plt.subplots(3,3)
df.groupby('identifier').plot(subplots=True)

to no avail. How can I create the graphs?

解决方案

Here's an automated layout with lots of groups (of random fake data) and playing around with grouped.get_group(key) will show you how to do more elegant plots.

import pandas as pd
from numpy.random import randint
import matplotlib.pyplot as plt


df = pd.DataFrame(randint(0,10,(200,6)),columns=list('abcdef'))
grouped = df.groupby('a')
rowlength = grouped.ngroups/2                         # fix up if odd number of groups
fig, axs = plt.subplots(figsize=(9,4), 
                        nrows=2, ncols=rowlength,     # fix as above
                        gridspec_kw=dict(hspace=0.4)) # Much control of gridspec

targets = zip(grouped.groups.keys(), axs.flatten())
for i, (key, ax) in enumerate(targets):
    ax.plot(grouped.get_group(key))
    ax.set_title('a=%d'%key)
ax.legend()
plt.show()

这篇关于如何通过子图创建 pandas 群组情节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆