如何绘制按 pandas 中的列名分组的箱线图?

How to plot a boxplot grouped by the column names in pandas?

我的数据框:

     Q   JJ    R    S   R'  S'    P    T   JJ    Q  ...    P    T   JJ    Q  \
0 -0.2  0.0  6.1 -1.0  0.0   0  0.6  2.1  0.0  0.0  ...  0.9  3.9 -0.3  0.0   
1 -0.6  0.0  7.2  0.0  0.0   0  0.4  1.5  0.0  0.0  ...  0.4  2.6 -0.5  0.0   
2  1.0  0.0  4.5 -2.8  0.0   0  0.3  2.5  0.8 -0.4  ...  0.4  3.4  0.9  0.0   
3  0.9  0.0  7.8 -0.7  0.0   0  1.1  1.9  0.1  0.0  ...  0.6  3.0  0.1  0.0   
4  0.0  0.0  5.2 -1.4  0.0   0  0.9  2.3  0.1  0.0  ... -0.2  2.9 -0.4  0.0   

      R    S   R'  S'    P    T  
0   9.0 -0.9  0.0   0  0.9  2.9  
1   8.5  0.0  0.0   0  0.2  2.1  
2   9.5 -2.4  0.0   0  0.3  3.4  
3  12.2 -2.2  0.0   0  0.4  2.6  
4  13.1 -3.6  0.0   0 -0.1  3.9 

我正在尝试绘制一个按列名分组的箱线图(有 8 个组,所以我希望有 8 个箱线图)。 我用过:

bp = df_net_wave_amplitude_for_std.plot.box(figsize=(20,8))

bp = df_net_wave_amplitude_for_std.boxplot(figsize=(20,8))

但我得到了 x 轴上的所有列,而不是让它们按名称分组:

我想通了: 首先我应该获取数据:

df_net_wave_amplitude_for_std = df_net_wave_amplitude_for_std.stack()

然后我整理了结果:重置索引,去掉一个冗余列(称为'level_0')并重命名列:

df_net_wave_amplitude_for_std = df_net_wave_amplitude_for_std.reset_index()
del df_net_wave_amplitude_for_std['level_0']
df_net_wave_amplitude_for_std.columns = ['Wave', 'data']

我终于可以使用箱线图功能了:

bp = df_net_wave_amplitude_for_std.boxplot('data', by='Wave', figsize=(20,8))