将标签与R中的plot3D包重叠



我目前正在使用R中的plot3D包创建一个3D散点图,我想为我的数据点添加数据标签。然而,我的一些数据点彼此具有相同的值,我想找到一种类似于ggrepel的解决方案,该解决方案可以将数据标签从点偏移,以便这些点的标签清晰可见。下面的示例代码:

library(plot3D)
names <- c("A", "B", "C", "D", "E")
x <- c(1,1,2,3,4)
y <- c(1,1,3,4,5)
z <- c(1,1,4,5,6)
scatter3D(x, y, z)
text3D(x,y,z, names, add = TRUE, cex = 1)

A和B的标签当前叠加在一起。

我也尝试使用directlabels包,但它似乎无法识别text3D或plot3D对象。任何帮助都将不胜感激。

plotrix::thigmophobe函数可确定方向,以尝试阻止标签在2D图中重叠。rgl没有任何等效功能,而且由于可以旋转绘图,因此始终可以将标签旋转到彼此的顶部。但是,下面的函数尝试为一个特定视图放置标签,这样它们就不会重叠。

thigmophobe.text3d <- function(x, y = NULL, z = NULL, texts, ...) {
xyz <- xyz.coords(x, y, z)
# Get the coordinates as columns in a matrix in
# homogeneous coordinates
pts3d <- rbind(xyz$x, xyz$y, xyz$z, 1)
# Apply the viewing transformations and convert 
# back to Euclidean
pts2d <- asEuclidean(t(par3d("projMatrix") %*% 
par3d("modelMatrix") %*% 
pts3d))
# Find directions so that the projections don't overlap
pos <- plotrix::thigmophobe(pts2d)
# Set adjustments for the 4 possible directions
adjs <- matrix(c(0.5, 1.2,   
1.2, 0.5,  
0.5, -0.2,  
-0.2, 0.5), 
4, 2, byrow = TRUE)
# Plot labels one at a time in appropriate directions.
for (i in seq_along(xyz$x)) 
text3d(pts3d[1:3, i], texts = texts[i], 
adj = adjs[pos[i],], ...)
}

上述函数存在一些问题:它基于rgl::text3d而不是plot3D::text3D,因此可选参数不同;它一次绘制一个标签,如果你有很多标签,这可能是低效的,它不做错误检查,等等。

编辑后添加:

rgl的未发布版本0.99.20添加了一个thigmophobe3d函数来实现这一点。你必须从https://r-forge.r-project.org/R/?group_id=234或Github镜像https://github.com/rforge/rgl目前。

最新更新