如何计算ggplot2绘制的椭圆的面积?

How to calculate the area of ellipse drawn by ggplot2?

在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()

你可以通过求椭圆的半长轴和半短轴来计算椭圆的面积(如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

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

您需要根据您想要获得的置信度来缩放方差/特征值。

This thread is very helpful

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 package (v0.3.0)

于 2020-02-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 package (v0.3.0)

于 2020-02-27 创建

计算出的值不同. This is likely due to the different calculation under the hood, with different assumptions on the underlying distribution. see this thread