【问题标题】:Seaborn multiple boxplot based by different conditions基于不同条件的 Seaborn 多重箱线图
【发布时间】:2021-11-27 02:20:35
【问题描述】:

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

我正在寻找的结果是使用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       |

感谢您的帮助。

【问题讨论】:

    标签: python pandas dataframe seaborn boxplot


    【解决方案1】:

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

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

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

    3. 我们的最终数据框df 只是df1df2 的串联。

    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')
      

    【讨论】:

      猜你喜欢
      • 2021-09-02
      • 2016-02-06
      • 2017-05-14
      • 2018-09-08
      • 2023-03-29
      • 2020-02-10
      • 2020-09-20
      • 2021-06-24
      • 1970-01-01
      相关资源
      最近更新 更多