如何用来自不同列的分组数据并排绘制箱线图

问题描述

我想将数据显示为与两个数值列相对应的两个类别列的并排方框图。

这是我的尝试

# create a list of our conditions
conditions_BPXSY1 = [
    (da['BPXSY1'] < 125),(da['BPXSY1'] >= 125) & (da['BPXSY1'] <= 174),(da['BPXSY1'] > 175)
    ]
conditions_BPXSY2 = [
    (da['BPXSY2'] < 125),(da['BPXSY2'] >= 125) & (da['BPXSY2'] <= 174),(da['BPXSY2'] > 175)
    ]

# create a list of the values we want to assign for each condition
values = ['< 125 mm Hg','125 – 174 mm Hg','175+ mm Hg']

# create a new column and use np.select to assign values to it using our lists as arguments
#da.dropna(inplace=True)
da['BPXSY1x'] = np.select(conditions_BPXSY1,values)
da['BPXSY2x'] = np.select(conditions_BPXSY2,values)

f,axes = plt.subplots(1,2,figsize=(13,6))
sns.Boxplot(x="BPXSY1x",y="BPXSY1",data=da,order=['< 125 mm Hg','175+ mm Hg'],orient='v',ax=axes[0])
sns.Boxplot(x="BPXSY2x",y="BPXSY2",ax=axes[1])

这是结果:

enter image description here

但是,我希望得到的结果看起来像J是BPXSY1,R是BPXSY2(当然,我没有S)

enter image description here

解决方法

  • 似乎只有一个数据帧,其中包含两列'BPXSY1''BPXSY2'
  • 数据可视化是关于重塑数据框,以发送到绘图API。
  • 与其堆叠在一起,不如将它们分开堆放,必须将带有研究标记的标签堆叠为一列,将血压堆叠在另一列中。
  • 使用pandas.cut对血压值进行分类和标记。
import pandas as pd
import seaborn as sns

# given dataframe df
   bpxsy1  bpxsy2
0      74    70.0
1      74    72.0
2      78    76.0

# stack the data columns
df = df.stack().reset_index(level=1).rename(columns={'level_1': 'stdy',0: 'bp'}).reset_index(drop=True)

# display(df)
     stdy    bp
0  bpxsy1  74.0
1  bpxsy2  70.0
2  bpxsy1  74.0

# bin the measurement values
bins = [0,125,150,175]
labels = ['< 125 mm Hg','125 - 150 mm Hg','150+ mm Hg']
df['bins'] = pd.cut(df.bp,bins=bins,labels=labels,right=False)

# display(df)
     stdy    bp         bins
0  bpxsy1  74.0  < 125 mm Hg
1  bpxsy2  70.0  < 125 mm Hg
2  bpxsy1  74.0  < 125 mm Hg

# plot
plt.figure(figsize=(9,7))
sns.boxplot(x='bins',y='bp',hue='stdy',data=df)

enter image description here