在值卡盘中的箱线图中绘制数据框

plot dataframe in boxplots in chucks of values

我有一个单列的Dataframe如下

df = pd.DataFrame(np.random.randn(20, 1),
                      columns=['Time'])
df['EDGE'] = pd.Series(['A', 'A', 'A','B', 'B', 'A', 'B','C','C', 'B','D','A','E','F','F','A','G','H','H','A'])
df

真实数据框有几十万行,唯一'EDGE'值列表大约有200

我想以箱线图的方式绘制结果如下:

boxplot = df.boxplot(by='EDGE')

现在有太多的值,我不得不打印一点,只是在同一个图中先说前 10 个字母。 另一方面,我想先打印平均时间较长的值。

预期结果: 箱线图的集合,每个箱线图包括 10 个 EDGE。方框按平均值降序排列 'TIME'.

如何进行?

我尝试了什么?

我尝试在 sub_df 上对每个值使用 loc,但之后每个箱线图只能得到一个框 我尝试使用 groupby 按“EDGE”进行分组但无济于事,因为我不知道如何仅绘制数据帧的前 n 组

注意:我假装使用尽可能少的库,即如果我可以使用 pandas 比使用 matplotlib 更好,并且 matplotlib 比在 matplotlib[=12= 之上使用另一个库更好]

IIUC,然后你可以通过重塑数据框来做到这一点

# define the number of edges per plot
nb_edges_per_plot = 4 #to change to your needs

# group by edge
gr = df.groupby('EDGE')['Time']
# get the mean per group and sort them 
order_ = gr.mean().sort_values(ascending=False).index
print (order_) #order depends on the random value so probably not same for you
#Index(['D', 'H', 'C', 'B', 'A', 'E', 'G', 'F'], dtype='object', name='EDGE')

# reshape your dataframe to ake each EDGE a column and order the columns
df_ = df.set_index(['EDGE', gr.cumcount()])['Time'].unstack(0)[order_]
print (df_.iloc[:5, :5])
# EDGE         D         H         C         B         A
# 0     1.729417  0.270593 -0.140786 -0.540270  0.862832
# 1          NaN  0.647830  1.038952 -0.129361 -0.648432
# 2          NaN       NaN       NaN -1.235637 -0.430890
# 3          NaN       NaN       NaN  0.631744 -1.622461
# 4          NaN       NaN       NaN       NaN  0.694052

现在您只需 boxplotgroupby。要在子图上绘制每组边,请执行:

df_.groupby(np.arange(len(order_))//nb_edges_per_plot, axis=1).boxplot()

或者如果你想要分开的数字,那么你可以这样做

for _, dfg_ in df_.groupby(np.arange(len(order_))//nb_edges_per_plot, axis=1):
    dfg_.plot(kind='box')

甚至在一行中你可以得到分隔的数字,看到区别在于使用 boxplot() 而不是使用 plot.box()。请注意,如果您想更改每个绘图中的参数,循环版本更灵活

df_.groupby(np.arange(len(order_))//nb_edges_per_plot, axis=1).plot.box()

您可以创建一个中间框架 groups,将 EDGE 分配给绘图编号(第 Order 列)和每个绘图中的 EDGE 位置(第 Pos 列)。

chunk_size = 3

groups = df.groupby('EDGE')
groups = (groups.ngroups - groups.Time.mean().rank(method='first').astype(int)).to_frame()
groups['Order'] = groups.Time // chunk_size
groups['Pos'] = groups.Time % chunk_size

for i in range(groups.Order.max() + 1):
    group = groups[groups.Order==i]
    df[df.EDGE.isin(group.index)].boxplot(by='EDGE', positions=group.Pos)

示例:

import pandas as pd
import numpy as np
np.random.seed(0)
df = pd.DataFrame(np.random.randn(20, 1), columns=['Time'])
df['EDGE'] = pd.Series(['A', 'A', 'A','B', 'B', 'A', 'B','C','C', 'B','D','A','E','F','F','A','G','H','H','A'])

# code from above ...

#verification:
print(df.groupby('EDGE').Time.mean().sort_values(ascending=False))
#EDGE
#G    1.494079
#B    1.367285
#E    0.761038
#A    0.442789
#F    0.282769
#D    0.144044
#H    0.053955
#C   -0.127288