- 将
boolean_value 设置为 x 轴,按单独的分类值绘制箱线图。
import pandas as pd
import numpy as np
import seaborn as sns
df = pd.DataFrame(np.random.rand(140, 1)*1000, columns=['int_value'])
df['boolean_value'] = np.random.random(df.shape)<0.5
sns.boxplot(y=df['int_value'], x=df['boolean_value'])
plt.show()
- 您在评论中要求添加数据点并不是箱线图的工作方式。但是,可以在顶部添加
swarmplot,以创建相同的效果。
sns.boxplot(y=df['int_value'], x=df['boolean_value'])
sns.swarmplot(y=df['int_value'], x=df['boolean_value'], color='black')
plt.show()
sns.boxplot(y=df['int_value'], x=df['boolean_value'][df['boolean_value']==True])
sns.swarmplot(y=df['int_value'], x=df['boolean_value'][df['boolean_value']==True], color='black')
plt.show()
- 如果您希望将整个分布作为单个箱线图,但只希望显示真实数据点。
sns.boxplot(y=df['int_value'])
sns.swarmplot(y=df['int_value'], x=df['boolean_value'][df['boolean_value']==True], color='black', label='only True')
plt.xticks([0], [''])
plt.xlabel('True/False Boxplot Distribution')
plt.legend()
plt.show()
注意:
- 对于样本数据,很难直观地辨别仅 True 数据的分布与 True/False 组合分布之间的差异。
df.describe()
int_value
count 140.000000
mean 524.828022
std 302.097860
min 1.566518
25% 240.890088
50% 567.986782
75% 778.906109
max 995.508649
df.groupby('boolean_value').describe()
int_value
count mean std min 25% 50% 75% max
boolean_value
False 70.0 525.125956 291.117406 1.566518 247.411473 577.119686 770.783246 995.508649
True 70.0 524.530087 314.800514 8.077607 233.074629 550.306306 828.866101 993.770101