如何构建按 ID 分组的多个 3D 椭圆?

How to build multiple 3D ellipses grouped by IDs?

如何围绕按 ID 分组的 3D 点构建多个 3D 椭圆?

以下示例显示了想要的结果:

# load data
data(iris)
head(iris)
# add column
iris$ID <- iris$Species
# change column values
within(iris, ID <- factor(ID, labels = 1:3))

# add variables
x <- sep.l <- iris$Sepal.Length
y <- pet.l <- iris$Petal.Length
z <- sep.w <- iris$Sepal.Width

x.set <- iris$Sepal.Length[(iris$Species == "setosa")]
y.set <- iris$Petal.Length[(iris$Species == "setosa")]
z.set <- iris$Sepal.Width[(iris$Species == "setosa")]

x.ver <- iris$Sepal.Length[(iris$Species == "versicolor")]
y.ver <- iris$Petal.Length[(iris$Species == "versicolor")]
z.ver <- iris$Sepal.Width[(iris$Species == "versicolor")]

x.vir <- iris$Sepal.Length[(iris$Species == "virginica")]
y.vir <- iris$Petal.Length[(iris$Species == "virginica")]
z.vir <- iris$Sepal.Width[(iris$Species == "virginica")]

# create 3D ellipses
ellips.set <- ellipse3d(cov(cbind(x.set, y.set, z.set)), centre = c(mean(x.set), mean(y.set), mean(z.set)), level = 0.9)
ellips.ver <- ellipse3d(cov(cbind(x.ver, y.ver, z.ver)), centre = c(mean(x.ver), mean(y.ver), mean(z.ver)), level = 0.9)
ellips.vir <- ellipse3d(cov(cbind(x.vir, y.vir, z.vir)), centre = c(mean(x.vir), mean(y.vir), mean(z.vir)), level = 0.9)

# plot
plot3d(x, y, z, col="black", box = FALSE, type ="s", radius = 0.10)

plot3d(ellips.set, col = "red", alpha = 0.5, add = TRUE, type = "wire")
plot3d(ellips.ver, col = "green", alpha = 0.5, add = TRUE, type = "wire")
plot3d(ellips.vir, col = "gold", alpha = 0.5, add = TRUE, type = "wire")

但是,与其手动创建省略号,不如在循环中创建。

   for (i in 1:length(iris$ID)) {
      ellipse.iris <- ellipse3d(cov(cbind(
           x=iris$Sepal.Length[(iris$ID == i)], y=iris$Petal.Length[(iris$ID == i)], z=iris$Sepal.Width[(iris$ID == i)])), 
           centre=c(mean(iris$Sepal.Length), mean(iris$Petal.Length), mean(levels(iris$Sepal.Width))), level = 0.95)
    }

不起作用。它抛出以下错误消息:

Error in chol.default(cov) : the leading minor of order 1 is not positive definite

你有一些问题。

首先,您要计算矩阵单行的协方差。最好有

for (id in unique(iris$ID))

中心计算则需要改为

centre=c(mean(iris$Sepal.Length[iris$ID == id]), 
       mean(iris$Petal.Length[iris$ID == id]), 
       mean(iris$Sepal.Width[iris$ID == id]))

然后你需要绘制它。所以循环应该是

for (id in unique(iris$ID)) {
      ellipse.iris <- ellipse3d(cov(cbind(
           x=iris$Sepal.Length[(iris$ID == id)], y=iris$Petal.Length[(iris$ID == id)], z=iris$Sepal.Width[(iris$ID == id)])), 
           centre=c(mean(iris$Sepal.Length[iris$ID == id]), 
             mean(iris$Petal.Length[iris$ID == id]), 
             mean(iris$Sepal.Width[iris$ID == id])), level = 0.95)
      shade3d(ellipse.iris, alpha = 0.3)
}