使用子图和循环绘制Pandas groupby组

fir*_*tup 6 python plot pandas subplot pandas-groupby

我正在尝试基于Pandas groupby对象生成子图的网格.我希望每个绘图都基于groupby对象的一组的两列数据.假数据集:

C1,C2,C3,C4
1,12,125,25
2,13,25,25
3,15,98,25
4,12,77,25
5,15,889,25
6,13,56,25
7,12,256,25
8,12,158,25
9,13,158,25
10,15,1366,25
Run Code Online (Sandbox Code Playgroud)

我试过以下代码:

import pandas as pd
import csv   
import matplotlib as mpl
import matplotlib.pyplot as plt
import math

#Path to CSV File
path = "..\\fake_data.csv"

#Read CSV into pandas DataFrame
df = pd.read_csv(path)

#GroupBy C2
grouped = df.groupby('C2')

#Figure out number of rows needed for 2 column grid plot
#Also accounts for odd number of plots
nrows = int(math.ceil(len(grouped)/2.))

#Setup Subplots
fig, axs = plt.subplots(nrows,2)

for ax in axs.flatten():
    for i,j in grouped:
        j.plot(x='C1',y='C3', ax=ax)

plt.savefig("plot.png")
Run Code Online (Sandbox Code Playgroud)

但它会生成4个相同的子图,每个子图上都绘制了所有数据(参见下面的示例输出):

在此输入图像描述

我想做以下的事情来解决这个问题:

for i,j in grouped:
    j.plot(x='C1',y='C3',ax=axs)
    next(axs)
Run Code Online (Sandbox Code Playgroud)

但是我得到了这个错误

AttributeError:'numpy.ndarray'对象没有属性'get_figure'

我将在我要绘制的groupby对象中拥有动态数量的组,以及比我提供的假数据更多的元素.这就是为什么我需要一个优雅的动态解决方案,并且每个组数据集都绘制在一个单独的子图上.

mcw*_*itt 11

听起来你想要并行地遍历组和轴,所以你想要这样的东西,而不是嵌套for循环(迭代每个轴的所有组).

for (name, df), ax in zip(grouped, axs.flat):
    df.plot(x='C1',y='C3', ax=ax)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

你在第二个代码片段中有正确的想法,但是你得到一个错误,因为它axs是一个轴数组,但plot只需要一个轴.所以它也应该next(axs)在你的例子中替换ax = axs.next()并更改plotto 的参数ax=ax.