我正在使用 R 中的数据集,其中包括与农业实践和结果相关的各种参数。这是我的数据框的简化结构:
df <- structure(list(peanutSeedToFood = c(1.41896783664886, 1.45277228739953,
2.45130326046724, 1.05434906990347, 2.5, 1.18856873091444), rotationCycle = c("ThreeYears",
"ThreeYears", "ThreeYears", "ThreeYears", "ThreeYears", "ThreeYears"), ownFallowUse = c("UseFallowIfNeeded", "UseFallowIfNeeded",
"UseFallowIfNeeded", "UseFallowIfNeeded", "UseFallowIfNeeded", "NeverUseFallow"), loanStrategy = structure(c(2L, 2L, 1L, 2L,
1L, 1L), .Label = c("AllExtraParcelsLoaner", "ExtraParcelsExceptFallowLoaner", "Selfish"), class = "factor"), ...), class = "data.frame")
数据框包含一个因子变量loanStrategy,具有三个级别:“AllExtraParcelsLoaner”、“ExtraParcelsExceptFallowLoaner”和“Selfish”。我感兴趣的是基于三个连续变量可视化每个组所占用的 3D 空间:objective.lastPopulation、objective.lastEffectiveFallowRatio 和 Objective.lastMilYield。
我已经能够使用 R 中的 Plotly 创建 3D 散点图。
plyply<- plot_ly(df, x=~objective.lastPopulation,
y=~objective.lastMilYield,
z=~-objective.lastEffectiveFallowRatio,
color=~loanStrategy, size=~rainFall)
plyply <- plyply %>% add_markers()
plyply
但现在我想更进一步,可视化包含该 3D 空间中每个组的点的凸包,本质上是可视化每个组占用的体积。
您可以使用 cxhull 包获取凸包的网格,并且可以使用 add_trace
和
type = "mesh3d"
使用 plotly绘制这样的网格。
library(plotly)
library(cxhull)
dat1 <- data.frame(
x = rgamma(12, 10, 1),
y = rgamma(12, 10, 1),
z = rgamma(12, 10, 1)
)
dat2 <- data.frame(
x = rgamma(12, 15, 1),
y = rgamma(12, 15, 1),
z = rgamma(12, 15, 1)
)
hull1 <- cxhull(as.matrix(dat1))
hull2 <- cxhull(as.matrix(dat2))
mesh1 <- hullMesh(hull1)
mesh2 <- hullMesh(hull2)
vertices1 <- mesh1$vertices
faces1 <- mesh1$faces
vertices2 <- mesh2$vertices
faces2 <- mesh2$faces
plot_ly() %>%
add_trace(
x = vertices1[, 1], y = vertices1[, 2], z = vertices1[, 3],
i = faces1[, 1] - 1, j = faces1[, 2] - 1, k = faces1[, 3] - 1,
type = "mesh3d",
opacity = 0.5, color = I("#121212")
) %>%
add_trace(
x = vertices2[, 1], y = vertices2[, 2], z = vertices2[, 3],
i = faces2[, 1] - 1, j = faces2[, 2] - 1, k = faces2[, 3] - 1,
type = "mesh3d",
opacity = 0.5, color = I("#121212")
)
然而,
color
的说法似乎没有效果。