6

在ggplot2中,在我使用stat_ellipse绘制椭圆图之后,有没有办法计算这个椭圆的面积?这是代码和情节:

library(ggplot2)
set.seed(1234)
x <- rnorm (1:1000)
y <- rnorm (1:1000)
data <- cbind(x, y)
data <- as.data.frame(data)
ggplot (data, aes (x = x, y = y))+
  geom_point()+
  stat_ellipse()

在此处输入图像描述

4

2 回答 2

10

您可以通过找到椭圆的半长轴和半短轴来计算椭圆的面积(如this SO answer所示):

# Plot object
p = ggplot (data, aes (x = x, y = y))+
  geom_point()+
  stat_ellipse(segments=201) # Default is 51. We use a finer grid for more accurate area.

# Get ellipse coordinates from plot
pb = ggplot_build(p)
el = pb$data[[2]][c("x","y")]

# Center of ellipse
ctr = MASS::cov.trob(el)$center  # Per @Roland's comment

# Calculate distance to center from each point on the ellipse
dist2center <- sqrt(rowSums((t(t(el)-ctr))^2))

# Calculate area of ellipse from semi-major and semi-minor axes. 
# These are, respectively, the largest and smallest values of dist2center. 
pi*min(dist2center)*max(dist2center)

[1] 13.82067
于 2016-08-05T06:34:36.107 回答
0

通过先计算特征值,可以直接从协方差矩阵计算面积。

您需要通过您想要获得的置信度因子来缩放方差/特征值。

这个线程非常有帮助

set.seed(1234)
dat <- data.frame(x = rnorm(1:1000), y = rnorm(1:1000))

cov_dat <- cov(dat) # covariance matrix

eig_dat <- eigen(cov(dat))$values #eigenvalues of covariance matrix

vec <- sqrt(5.991* eig_dat) # half the length of major and minor axis for the 95% confidence ellipse

pi * vec[1] * vec[2]  
#> [1] 18.38858

reprex 包(v0.3.0)于 2020 年 2 月 27 日创建

在这种特殊情况下,协方差为零,特征值或多或少是变量的方差。因此,您可以仅使用方差进行计算。- 假设两者都是正态分布的。

set.seed(1234)
data <- data.frame(x = rnorm(1:1000), y = rnorm(1:1000))

pi * 5.991 * sd(data$x) * sd(data$y) # factor for 95% confidence = 5.991
#> [1] 18.41814

reprex 包(v0.3.0)于 2020 年 2 月 27 日创建

计算的值与用户 eipi10 的回答不同。这可能是由于底层计算不同,对底层分布的假设不同。看到这个线程

于 2020-02-27T13:54:53.523 回答