python - 使用子图和循环按组绘制 Pandas

标签 python pandas plot 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

我试过下面的代码:

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 个相同的子图,每个子图都绘制了所有数据(参见下面的示例输出):

enter image description here

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

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

但是我得到了这个错误

AttributeError: 'numpy.ndarray' object has no attribute 'get_figure'

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

最佳答案

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

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

enter image description here

你在第二个代码片段中的想法是正确的,但是你得到了一个错误,因为 axs 是一个轴数组,但是 plot 只需要一个轴.因此,将示例中的 next(axs) 替换为 ax = axs.next() 并将 plot 的参数更改为ax=ax.

关于python - 使用子图和循环按组绘制 Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30379645/

相关文章:

python - uwsgi spooler 的执行模型是什么?

python - TypeError : Improper input: N=3 must not exceed M=1, 不确定我的尺寸有什么问题?

python - 当给定非均匀样本时,如何限制 Python 中 InterpolatedUnivariateSpline 中的插值区域?

r - 如何隐藏 corrplot 的选定相关性?

r - 在给定其他变量的情况下显示一个变量的存在百分比

python - 为什么 MATLAB 在使用 "from tensorflow import keras"调用 python 脚本时会产生错误?

python - 如何在 Pandas Python 中使用电子邮件 ID 查找连续记录

python - 在数据框中选择每个月的特定日期数据

python - 相当于 Pandas 的numpy

python - 绘制多轴离线时间序列图