【发布时间】:2021-03-26 18:18:39
【问题描述】:
我需要绘制一个 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()
【问题讨论】:
-
请阅读如何制作minimal reproducible example 并为
b_p_quad提供值 -
你有一个你想看的例子吗?目前尚不清楚 95% CI 椭圆与示例中的数据应该是什么样子
标签: python confidence-interval ellipse