【问题标题】:Plotting Pandas groupby groups using subplots and loop使用子图和循环绘制 Pandas groupby 组
【发布时间】:2015-08-03 11:16:37
【问题描述】:

我正在尝试根据 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

我已经尝试了以下代码:

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

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

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

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

但我收到此错误

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

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

【问题讨论】:

    标签: python pandas plot subplot pandas-groupby


    【解决方案1】:

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

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

    您在第二个代码 sn-p 中的想法是正确的,但您遇到了错误,因为 axs 是一个轴数组,但 plot 只需要一个轴。因此,将示例中的next(axs) 替换为ax = axs.next() 并将plot 的参数更改为ax=ax 也应该有效。

    【讨论】:

      猜你喜欢
      • 2014-09-23
      • 2018-05-13
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      • 2020-11-03
      • 2021-12-27
      相关资源
      最近更新 更多