【问题标题】:Overlapping labels with the plot3D package in R与 R 中的 plot3D 包重叠标签
【发布时间】:2018-07-31 15:48:55
【问题描述】:

我目前正在使用 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 对象。任何帮助将不胜感激。

【问题讨论】:

    标签: r rgl plot3d


    【解决方案1】:

    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 获取它。

    【讨论】:

      猜你喜欢
      • 2014-06-06
      • 2013-11-03
      • 2016-05-25
      • 2019-05-11
      • 1970-01-01
      • 2016-08-15
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多