微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python中的椭圆95%置信区间

如何解决python中的椭圆95%置信区间

我需要绘制一个 95% 置信区间的椭圆,但它不起作用。显然代码没有错误,但情节很奇怪,我不知道如何解决

x 和 y 是来自引导的 1000 个值的列表。情节只是一条线:

plot

def confidence_ellipse(x,y,ax,n_std=3,facecolor='none',**kwargs):

    """

    Create a plot of the covariance confidence ellipse of *x* and *y*,Parameters
    -----------
    x,y: array-like,shape (n,)
        Input data
    ax: matplotlib.axes.Axes
        The axes object to draw the ellipse into
    n_std: float
        The number of standart deviations to determine the ellipse's radiuses.
    **kwargs
            Forward to '~matplotlib.patches.Ellipse'
    
    Returns
    -----------
    matplotlib.patches.Ellipse
    """
    if x.size != y.size:
        raise ValueError("x and y must be the same size")
    cov = np.cov(x,y)
    pearson = cov[0,1]/np.sqrt(cov[0,0] * cov[1,1])
    # Using a special case to obtain the eigenvalues of this two-dimensional dataset
    ell_radius_x = np.sqrt(1+pearson)
    ell_radius_y = np.sqrt(1-pearson)
    ellipse = Ellipse((0,0),width=ell_radius_x * 2,height=ell_radius_y * 2,facecolor=facecolor,**kwargs)
    
    # Calculating the standart deviation of x from the square root of the variance
    # and multiplying with the given number of std deviation
    
    scale_x = np.sqrt(cov[0,0]) * n_std
    mean_x = np.mean(x)
    
    # Calculating the std deviation of y...
    scale_y = np.sqrt(cov[1,1]) * n_std
    mean_y = np.mean(y)
    
    transf = transforms.Affine2D() \
        .rotate_deg(45) \
        .scale(scale_x,scale_y) \
        .translate(mean_x,mean_y)
    
    ellipse.set_transform(transf + ax.transData)
    return ax.add_patch(ellipse)

##############

y = b_p_quad[:,0]

x = b_p_quad[:,1]


fig = plt.figure(figsize = (7,7),dpi = 400)

ax = fig.add_subplot()

ax.scatter(x,s=0.7,color = 'slategrey')

ax.scatter(np.mean(x),np.mean(y),color='navy')

confidence_ellipse(x,n_std=1.96,edgecolor='red',facecolor='cornflowerblue',alpha=0.1)

ax.set_xlabel('Intercept (b)')

ax.set_ylabel('Slope (a)')

plt.show()

解决方法

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。