Python Seaborn Boxplot:在晶须上叠加 95 个百分位值 [英] Python Seaborn Boxplot: Overlay 95 percentile values on whisker

查看:30
本文介绍了Python Seaborn Boxplot:在晶须上叠加 95 个百分位值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 seaborn 箱线图上叠加 95 个百分位值.我无法弄清楚叠加文字的方式,或者是否有适合自己的功能.我将如何修改以下代码以覆盖图上95个百分点的值.

将pandas导入为pd将numpy导入为np将 seaborn 作为 sns 导入df = pd.DataFrame(np.random.randn(200, 4), columns=list('ABCD'))*100字母 = 列表('AB')df['Gr'] = np.random.choice(np.array(alphabet, dtype="|S1"), df.shape[0])df_long = pd.melt(df, id_vars=['Gr'], value_vars = ['A','B','C','D'])sns.boxplot(x ="variable",y ="value",色相='Gr',数据= df_long,whis = [5,95])

解决方案

考虑 seaborn 的 plot.text,借鉴自

I want to overlay 95 percentile values on seaborn boxplot. I could not figure out the ways to overlay text or if there is seaborn capability for that. How would I modify following code to overlay the 95 percentile values on plot.

import pandas as pd
import numpy as np
import seaborn as sns
df = pd.DataFrame(np.random.randn(200, 4), columns=list('ABCD'))*100
alphabet = list('AB')
df['Gr'] = np.random.choice(np.array(alphabet, dtype="|S1"), df.shape[0])
df_long = pd.melt(df, id_vars=['Gr'], value_vars = ['A','B','C','D'])
sns.boxplot(x = "variable", y="value", hue = 'Gr',  data=df_long, whis = [5,95])

解决方案

Consider seaborn's plot.text, borrowing from @bernie's answer (also a healty +1 for including sample dataset). The only challenge is adjusting the alignment due to grouping in hue field to have labels overlay over each boxplot series. Even have labels color coded according to series.

import pandas as pd
import numpy as np
import seaborn as sns

np.random.seed(61518)
# ... same as OP

# 95TH PERCENTILE SERIES
pctl95 = df_long.groupby(['variable', 'Gr'])['value'].quantile(0.95)
pctl95_labels = [str(np.round(s, 2)) for s in pctl95]

# GROUP INDEX TUPLES
grps = [(i, 2*i, 2*i+1) for i in range(4)]
# [(0,0,1), (1,2,3), (2,4,5), (3,6,7)]

pos = range(len(pctl95))

# ADJUST HORIZONTAL ALIGNMENT WITH MORE SERIES
for tick, label in zip(grps, hplot.get_xticklabels()):
    hplot.text(tick[0]-0.1, pctl95[tick[1]] + 0.95, pctl95_labels[tick[1]], 
               ha='center', size='x-small', color='b', weight='semibold')

    hplot.text(tick[0]+0.1, pctl95[tick[2]] + 0.95, pctl95_labels[tick[2]], 
               ha='center', size='x-small', color='g', weight='semibold')
sns.plt.show()

这篇关于Python Seaborn Boxplot:在晶须上叠加 95 个百分位值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆