如何创建带子块的Pandas分组图?

2024-05-19 10:08:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的数据框:

     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

所以我对每个标识符进行分组:

df.groupby('identifier')

现在我想在网格中生成子块,每组一个图。我两个都试过了

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

或者

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

以及

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

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


Tags: 数据falsetrue网格dfplotvalue图表
3条回答

使用pivot获取列中的identifiers,然后打印

pd.pivot_table(df.reset_index(),
               index='index', columns='identifier', values='value'
              ).plot(subplots=True)

enter image description here

并且,输出

pd.pivot_table(df.reset_index(),
               index='index', columns='identifier', values='value'
               )

看起来像-

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

这里有一个包含许多组(随机伪数据)的自动布局,使用grouped.get_group(key)将向您展示如何进行更优雅的绘图。

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()

enter image description here

如果你有一个多索引的序列。这是另一个通缉图的解决方案。

df.unstack('indentifier').plot.line(subplots=True)

相关问题 更多 >

    热门问题