gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:55:24 26 4
gpt4 key购买 nike

在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

最佳答案

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

关于r - 如何计算ggplot2绘制的椭圆面积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38782051/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com