pandas 将α面积(置信区间)添加到SNS点图

rn0zuynd  于 2023-11-15  发布在  其他
关注(0)|答案(1)|浏览(122)

假设一个框架

df = pd.DataFrame({"X" : [1, 1, 2, 2, 3, 3, 4, 4], 
                   "Model" : ["A", "B", "A", "B", "A", "B", "A", "B"],
                   "Lower" : [0.2, 0.3, 0.2, 0.2, 0.25, 0.3, 0.3, 0.25],
                   "Median" : [0.5, 0.55, 0.6, 0.55, 0.5, 0.6, 0.5, 0.5],
                   "Upper" : [0.6, 0.7, 0.65, 0.7, 0.7, 0.65, 0.55, 0.7]})

字符串
一个plot:

pl1 = sns.catplot(data = df, kind = 'point', 
            hue = 'Model', 
            x = 'X', 
            y = 'Median', sharey = False, heigth = 3, aspect = 1.5)
pl1.set(ylim = (0, 1))


看起来像这样的


的数据
我想做的是基于列Lower和'Upper'添加一个置信区间,例如,看起来像这样(对于蓝色曲线)



这可能吗?

7eumitmz

7eumitmz1#

为了得到类似的蓝色区域,更新下限和上限值。绘图部分可以用matplotlib.pyplot处理。

验证码:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame({"X": [1, 1, 2, 2, 3, 3, 4, 4],
                   "Model": ["A", "B", "A", "B", "A", "B", "A", "B"],
                   "Lower": [0.4, 0.3, 0.45, 0.2, 0.40, 0.3, 0.45, 0.25],
                   "Median": [0.5, 0.55, 0.6, 0.55, 0.5, 0.6, 0.5, 0.5],
                   "Upper": [0.6, 0.7, 0.65, 0.7, 0.65, 0.65, 0.65, 0.7]})

pl1 = sns.catplot(data=df, kind='point', hue='Model', x='X', y='Median', sharey=False, height=3, aspect=1.5, legend=False)

# fill the area between lower and upper for Model A in blue
model_a_lower = df[df['Model'] == 'A']['Lower'].values
model_a_upper = df[df['Model'] == 'A']['Upper'].values
model_a_x = df[df['Model'] == 'A']['X'].values
model_a_x = model_a_x - model_a_x[0]   # to make it => model_a_x = [0, 1, 2, 3] due to fill_between function start and end points.

plt.fill_between(x=model_a_x, y1=model_a_lower, y2=model_a_upper, alpha=0.2, color='blue')
pl1.set(ylim=(0, 1))
plt.show()

字符串

输出:


的数据

相关问题