2016-08-05 7 views
4

В ggplot2, после того, как я рисую график эллипса с использованием stat_ellipse, есть ли способ вычислить область этого эллипса? Вот код и сюжет:Как рассчитать площадь эллипса, нарисованную ggplot2?

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

ответ

7

Вы можете вычислить площадь эллипса, найдя его полуглавной и полуавтоматических мелкие оси (как показано в 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 
+2

Вы можете более точно рассчитать центр с помощью 'MASS :: cov.trob (cbind (x, y)) $ center', что является' stat_ellipse' [по умолчанию] (https://github.com/hadley /ggplot2/blob/master/R/stat-ellipse.R#L96). – Roland

+0

Спасибо @Roland. Я обновил свой ответ соответственно. – eipi10