如何计算ggplot2绘制的椭圆的面积? [英] How to calculate the area of ellipse drawn by ggplot2?

查看:169
本文介绍了如何计算ggplot2绘制的椭圆的面积?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ggplot2中,使用stat_ellipse绘制椭圆图后,有什么方法可以计算此椭圆的面积吗?这是代码和情节:

In ggplot2, after I drawing the ellipse plot using stat_ellipse, is there any way to calculate the area of this ellipse? Here is the code and the plot:

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

推荐答案

您可以通过找到椭圆的半长轴和半短轴来计算椭圆的面积(如

You can calculate the area of the ellipse by finding its semi-major and semi-minor axes (as shown in 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

这篇关于如何计算ggplot2绘制的椭圆的面积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆