【问题标题】:How to plot side by side boxplots with grouped data from different columns如何使用来自不同列的分组数据并排绘制箱线图
【发布时间】:2021-01-20 03:57:59
【问题描述】:

我想将我的数据可视化为对应于两个数值列的两个分类列上的并排箱线图。

这是我的尝试

# 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', '125 – 174 mm Hg', '175+ mm Hg'],  orient='v' , ax=axes[0])
sns.boxplot(x="BPXSY2x", y="BPXSY2", data=da, order=['< 125 mm Hg', '125 – 174 mm Hg', '175+ mm Hg'],  orient='v' , ax=axes[1])

结果如下:

但是,我希望 J 是 BPXSY1,R 是 BPXSY2 的结果(当然,我没有 S)

【问题讨论】:

    标签: python pandas seaborn boxplot categorical-data


    【解决方案1】:
    • 看起来有一个包含两列 '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)
    

    【讨论】:

      猜你喜欢
      • 2017-03-13
      • 2016-10-30
      • 1970-01-01
      • 2020-04-29
      • 2011-02-03
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多