首页 > 解决方案 > 基于不同条件的 Seaborn 多重箱线图

问题描述

我有一个包含两列的数据框。功率列代表系统的功耗。component_status 列根据组件何时关闭或打开,将数据分为两部分。当值为 153 时,表示组件为 ON,当值为 150 时,表示组件为 OFF。

我正在寻找的结果是有一个带有三个箱线图的箱线图,使用sns.boxplot. 一种是所有数据的功耗,称为“TOTAL”。另外两个,基于组件是关闭还是打开的功耗,称为“COMPONENT = ON”“COMPONENT = OFF”。

数据框示例如下:

power|component_status |
 0.5 |       150       | 
 1.5 |       150       | 
 2.5 |       150       |
 0.3 |       153       |
 0.5 |       153       | 
 1.5 |       153       | 
 2.5 |       150       |
 0.3 |       153       |

谢谢您的帮助。

标签: pythonpandasdataframeseabornboxplot

解决方案


您的第一步是根据条件构建数据框。有几种方法可以解决这个问题。

  1. 让我们从您给出的初始df1(数据帧#1)开始。然后,让我们添加一condition列来表示“总计”。您可以使用它print(df1)来查看它的外观。

  2. 然后让我们将该数据框复制到df2中,并将 替换为conditions中的关闭/开启条件component_status

  3. 我们的最终数据框df只是df1和的串联df2

  4. 现在我们有了一个df可以在 Seaborn 中使用的数据框。

    ### Set up
    import pandas as pd
    import numpy as np
    import seaborn as sns
    
    power = [0.5, 1.5, 2.5, 0.3, 0.5, 1.5, 2.5, 0.3]
    component_status = [150, 150, 150, 153, 153, 153, 150, 153]
    df1 = pd.DataFrame(
        data=zip(power, component_status), columns=["power", "component_status"]
    )
    
    ### Step 1
    df1["condition"] = "Total"
    # print(df1)
    
    ### Step 2
    df2 = df1.copy()
    
    df2["condition"] = np.where(df2["component_status"] == 153, "On", "Off")
    
    ### If you have several criteria, it can be easier to use np.select
    ### ... or just use Pandas directly:
    # df2.loc[(df2['component_status'] == 153), 'condition'] = 'On'
    # df2.loc[(df2['component_status'] == 150), 'condition'] = 'Off'
    
    ### Step 3
    df = pd.concat([df1,df2])
    print(df)
    
    ### Step 4
    sns.boxplot(data=df, x='condition', y='power')
    

在此处输入图像描述 在此处输入图像描述


推荐阅读