这篇帖子是我关于how to draw polar dendrogram in 3D in rgl的问题的延伸.用户2554330的回答解决了这个问题.现在,我想在树状图的顶端进一步添加3D网格.
这构成了树状图:
a <- list() # initialize empty object
# define merging pattern:
# negative numbers are leaves,
# positive are merged clusters (defined by row number in $merge)
a$merge <- matrix(c(-1, -2,
-3, -4,
1, 2), nc=2, byrow=TRUE )
a$height <- c(1, 1.5, 3) # define merge heights
a$order <- 1:4 # order of leaves(trivial if hand-entered)
a$labels <- LETTERS[1:4] # labels of leaves
class(a) <- "hclust" # make it an hclust object
plot(a) # show it
# Convert to a dendrogram object.
ad <- as.dendrogram(a)
# dend_data contains segment information
library(ggdendro)
dend_data <- dendro_data(ad, type = "rectangle")
来自用户2554330的代码以3D形式绘制了树状图:
nodes <- dend_data$segments
# Set the gap between the ends of the tree
gap <- 0
# Set the offset from the center.
offset <- 0
radius <- with(nodes, max(c(y, yend)) + offset)
circ <- with(nodes, max(c(x, xend)) + gap)
# Convert to polar coordinates
nodes$theta <- with(nodes, 2*pi*x/circ)
nodes$thetaend <- with(nodes, 2*pi*xend/circ)
nodes$r <- with(nodes, (radius - y)/radius)
nodes$rend <- with(nodes, (radius - yend)/radius)
# Extract the horizontal and vertical segments
horiz <- subset(nodes, y == yend)
vert <- subset(nodes, x == xend)
library(rgl)
open3d()
#> glX
#> 1
# Draw the vertical segments, which are still segments
x <- with(vert, as.numeric(rbind(r*cos(theta), rend*cos(theta))))
y <- with(vert, as.numeric(rbind(r*sin(theta), rend*sin(theta))))
segments3d(x, y, z = 0)
# Draw the horizontal segments, which are now arcs. Zero
# radius arcs are dropped
horiz <- subset(horiz, r > 0)
with(horiz, arc3d(from = cbind(r*cos(theta), r*sin(theta), 0),
to = cbind(r*cos(thetaend), r*sin(thetaend), 0),
center = c(0, 0, 0)))
# Draw the labels
labels <- dend_data$labels
labels$theta <- with(labels, 2*pi*x/circ)
# Add a bit to the y so the label doesn't overlap the segment
labels$r <- with(labels, (radius - y)/radius + 0.1)
with(labels, text3d(r*cos(theta), r*sin(theta), 0, label))
现在我在树状图的顶端添加球体:
with(labels, spheres3d(r*cos(theta), r*sin(theta), 0, radius = 0.1, color = c("lightblue", "pink", "lightyellow", "lightgrey")))
当我旋转RGL场景时,所有四个球体与3D树状图一起旋转.我想问有没有一种方法可以在RGL窗口中交互地单独旋转每个球体,这样当我旋转粉色球体时,3D树状图不会旋转,其他3个球体也不会旋转.谢谢.