简体   繁体   English

python 中的椭圆 95% 置信区间

[英]Ellipse 95% confidence interval in python

I need to plot an ellipse of 95% confidence interval, but is it not working.我需要 plot 一个 95% 置信区间的椭圆,但它不起作用。 Apparently there is no error in the code, but the plot is weird and I don't know how to fix it.显然代码中没有错误,但是 plot 很奇怪,我不知道如何修复它。

x and y are a list of 1000 values from bootstrapping. x 和 y 是来自自举的 1000 个值的列表。 The plot is just a line: 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,y, s=0.7, color = 'slategrey')

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

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

ax.set_xlabel('Intercept (b)')

ax.set_ylabel('Slope (a)')

plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM