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

时间:2016-08-05 05:55:25

标签: r ggplot2 r-car

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

enter image description here

2 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:0)

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

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

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创建

计算出的值是不同的from user eipi10's answer。这可能是由于引擎盖下的计算不同,对基础分布的假设不同。 see this thread