[英]Multiple boxplots based on conditions
我有一個帶有兩列的 dataframe。 功率列表示系統的功耗。 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 |
謝謝您的幫助。
您的第一步是根據條件構建數據框。 有幾種方法可以go了解一下。
df1
(數據幀 #1)開始。 然后,讓我們添加一個condition
列來表示“總計”。 您可以使用print(df1)
來查看它的外觀。df2
中,並用component_status
中的關閉/打開條件替換conditions
。df
只是df1
和df2
的串聯。df
准備好到 Seaborn 中的 go。# 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])
df
視圖 power component_status condition
0 0.5 150 Total
1 1.5 150 Total
2 2.5 150 Total
3 0.3 153 Total
4 0.5 153 Total
5 1.5 153 Total
6 2.5 150 Total
7 0.3 153 Total
0 0.5 150 Off
1 1.5 150 Off
2 2.5 150 Off
3 0.3 153 On
4 0.5 153 On
5 1.5 153 On
6 2.5 150 Off
7 0.3 153 On
# Step 4
ax = sns.boxplot(data=df, x='condition', y='power')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.