python - python中的椭圆95%置信区间
问题描述
我需要绘制一个 95% 置信区间的椭圆,但它不起作用。显然代码中没有错误,但情节很奇怪,我不知道如何修复它。
x 和 y 是来自自举的 1000 个值的列表。情节只是一条线:
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()
解决方案
推荐阅读
- javascript - 如何更新嵌套的useState?
- laravel - Laravel Cashier (Stripe) 自定义 Webhook 未收到 $payload
- ruby-on-rails - 推送 Rails 应用程序时如何修复 heroku 错误
- linux - .bashrc 中的 Julia 别名无法正常工作
- c++ - 替代 C++ std::vector 的两个指针
- c++ - 由于“make: *** No rule to make target `run'”,无法在 Mac 上编译 or-tools 示例。
- node.js - 为什么 react+nodejs 应用程序部署到 heroku 显示应用程序错误?
- d3.js - d3 地理投影从正交过渡到 X
- javascript - 在 ReactJS 中捕捉滚动和渲染时间导致浏览器在错误的位置启动
- r - 解决自定义函数中的范围问题以从“htest”对象中提取数据