2016-08-05 20 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

あなたは 'stat_ellipse'がデフォルトで使う' MASS :: cov.trob(cbind(x、y))$ center'を使ってより正確に中心を計算することができます(https://github.com/hadley /ggplot2/blob/master/R/stat-ellipse.R#L96)。 – Roland

+0

ありがとう@Roland。私はそれに応じて私の答えを更新しました。 – eipi10

関連する問題