使用 pandas 绘图在 groupby 之后进行子绘图

Subplotting after groupby with pandas plot

我有一个这样的数据框:

df = pd.DataFrame({"idx":[1,2,3]*2,"a":[1]*3+[2]*3,'b':[3]*3+[4]*3,'grp':[4]*3+[5]*3})
df = df.set_index("idx")
df
     a  b  grp
idx           
1    1  3    4
2    1  3    4
3    1  3    4
1    2  4    5
2    2  4    5
3    2  4    5

我想绘制 ab 的值作为 idx 的函数。每列制作一个子图,每组制作一行。

我设法做到这一点,分别创建轴并按照建议迭代组 。但我想使用绘图函数的 subplots 参数来避免循环。 我试过像

这样的解决方案
df.groupby("grp").plot(subplots=True)

但是它将组绘制在不同的子图中并且删除 groupby 不会像示例中那样出现两条分隔线。

可能吗?迭代和使用 matplotlib plot 还是使用 pandas plot 函数更好?

如果我理解你的问题是正确的,你可以访问 pandas 数据框中的列和行。一个例子可以是这样的:

import numpy as np
import matplotlib.pyplot as plt
x = np.array(df['idx']) 

a = np.array(df['a']) 

b = np.array(df['b']) 

plt.subplot(1,2,1)#(121) will also work
#fill inn title etc for the first plot under here
plt.plot(x,a)
plt.subplot(1,2,2)
#fill inn title etc for the second plot under here
plt.plot(x,b)
plt.show()

编辑:抱歉现在更改了子图。

IIUC,你可以这样做:

axs = df.set_index('grp', append=True)\
  .stack()\
  .unstack('grp')\
  .rename_axis(['idx','title'])\
  .reset_index('title').groupby('title').plot()

[v.set_title(f'{i}') for i, v in axs.items()]

输出:

也许可以简化简单的循环和绘图:

fig, ax = plt.subplots(1,2, figsize=(10,5))
ax = iter(ax)
for n, g in df.set_index('grp', append=True)\
              .stack()\
              .unstack('grp')\
              .rename_axis(['idx','title'])\
              .reset_index('title').groupby('title'):
    g.plot(ax=next(ax), title=f'{n}')

输出: