为何Seaborn与Plotly箱线图四分位数不一致?如何让二者输出相同结果
测试操作步骤
Seaborn
- 导入库并加载数据
import pandas as pd import seaborn as sns from matplotlib import pyplot as plt sns.set_theme(style="whitegrid", palette="muted") # Set2, muted, pastel, colorblind # Load the data import plotly.express as px df = px.data.gapminder() df.head()
- 展示箱线图及四分位数
sns.boxplot( data=df[df.year==2007], x='lifeExp', orient="h", ); print('q1', df[df.year==2007]['lifeExp'].quantile(.25)) print('median', df[df.year==2007]['lifeExp'].median()) print('q3', df[df.year==2007]['lifeExp'].quantile(.75)) plt.show()
Plotly
- 展示箱线图及四分位数
fig_box = px.box(df[df.year==2007], x='lifeExp', orientation='h', width=500, height=300) fig_box.show()
四分位数差异核心原因
二者默认采用的分位数计算规则不同:
- Seaborn的箱线图直接复用pandas的
quantile()计算结果,pandas默认使用interpolation='linear'的线性插值分位数规则。 - Plotly箱线图默认采用Tukey exclusive规则,计算Q1、Q3时会先排除中位数,再分别取上下半段数据的中位数作为分位值。
统一四分位数结果的调整方法
最简便的方式是调整Plotly的quartilemethod参数对齐Seaborn的默认计算规则,修改后代码如下:
fig_box = px.box(df[df.year==2007], x='lifeExp', orientation='h', width=500, height=300, quartilemethod='linear') # 新增本参数指定线性插值规则 fig_box.show()
如果需要让Seaborn对齐Plotly的默认输出,修改pandas计算分位数时的插值参数即可:
# 对齐Plotly默认exclusive规则的分位数计算 q1 = df[df.year==2007]['lifeExp'].quantile(.25, interpolation='midpoint') median = df[df.year==2007]['lifeExp'].median() q3 = df[df.year==2007]['lifeExp'].quantile(.75, interpolation='midpoint')
内容的提问来源于stack exchange,提问作者Elizio Era
相关产品推荐
相关产品推荐

