无重叠的抖动点

Tje*_*ebo 2 plot r scatter overlap ggplot2

我的数据:

a <- sample(1:5, 100, replace = TRUE)
b <- sample(1:5, 100, replace = TRUE)
c <- sample(1:10, 100, replace = TRUE)
d <- sample(1:40, 100, replace = TRUE)
df <- data.frame(a, b, c, d)
Run Code Online (Sandbox Code Playgroud)

使用ggplot2,我在 x = a 和 y = b 上创建了散点图,并在二维上加权(通过colour = csize = d)。请注意,x 和 y 是故意的1:5

显然,不同大小和颜色的点因此重叠,所以我尝试抖动以避免重叠:

ggplot(df, aes(a, b, colour = c, size = d)) + 
  geom_point(position = position_jitter())
Run Code Online (Sandbox Code Playgroud)

现在我希望这些点聚集得更紧密,所以我尝试了抖动函数height和的几种组合width,例如

ggplot(df, aes(a, b, colour = c, size = d)) + 
  geom_point(position = position_jitter(width = 0.2, height = 0.2))
Run Code Online (Sandbox Code Playgroud)

抖动使点仍然重叠,并将它们随机分布在给定区域上。

有没有办法让这些点完全不重叠,但尽可能紧密地聚集在一起,甚至可能接触,但又不“并排”或堆叠?(在某种程度上,用较小的点产生某种气泡)?

谢谢!

Mar*_*dri 5

根据@Tjebo的建议,我已将点排列在“堆”中。

set.seed(1234)
n <- 100
a <- sample(1:5,n,rep=TRUE)
b <- sample(1:5,n,rep=TRUE)
c <- sample(1:10,n,rep=TRUE)
d <- sample(1:40,n,rep=TRUE)
df0 <- data.frame(a,b,c,d)

# These parameters need carefully tuning
minr <- 0.05
maxr <- 0.2
# Order circles by dimension
ord <- FALSE

df1 <- df0
df1$d <- minr+(maxr-minr)*(df1$d-min(df1$d))/(max(df1$d)-min(df1$d))
avals <- unique(df1$a)
bvals <- unique(df1$b)

for (k1 in seq_along(avals)) {
  for (k2 in seq_along(bvals)) {
  print(paste(k1,k2))
    subk <- (df1$a==avals[k1] & df1$b==bvals[k2])
    if (sum(subk)>1) {
      subdfk <- df1[subk,]
      if (ord) {
        idx <- order(subdfk$d)
        subdfk <- subdfk[idx,]
      }
      subdfk.mod <- subdfk
      posmx <- which.max(subdfk$d)   
      subdfk1 <- subdfk[posmx,]
      subdfk2  <- subdfk[-posmx,]
      angsk <- seq(0,2*pi,length.out=nrow(subdfk2)+1)
      subdfk2$a <- subdfk2$a+cos(angsk[-length(angsk)])*(subdfk1$d+subdfk2$d)/2
      subdfk2$b <- subdfk2$b+sin(angsk[-length(angsk)])*(subdfk1$d+subdfk2$d)/2
      subdfk.mod[posmx,] <- subdfk1
      subdfk.mod[-posmx,] <- subdfk2
      df1[subk,] <- subdfk.mod
    }
  }
}

library(ggplot2)
library(ggforce)
ggplot(df1, aes()) + 
  geom_circle(aes(x0=a, y0=b, r=d/2, fill=c), alpha=0.7)+ coord_fixed()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述