抖动点无重叠 [英] Jitter dots without overlap
问题描述
我的数据:
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)
使用 ggplot2
,我在x = a和y = b上创建了散点图,并在二维方向上加权(通过 colour = c
和 size = d
).请注意,x和y故意是 1:5
.
Using ggplot2
, I have created scatterplot over x = a and y = b, weighted in two dimension (by colour = c
and size = d
). Note that x and y are intentionally 1:5
.
很明显,不同大小和颜色的点因此重叠,所以我尝试通过抖动来避免重叠:
Obviously, the points of different sizes and colors therefore overlap, so I tried jitter to avoid overlapping:
ggplot(df, aes(a, b, colour = c, size = d)) +
geom_point(position = position_jitter())
现在,我希望将点聚集在一起,所以我尝试了几个抖动功能的 height
和 width
的组合,例如
Now I would like the dots clustering closer together, so I tried several
combinations of height
and width
for the jitter function, such as
ggplot(df, aes(a, b, colour = c, size = d)) +
geom_point(position = position_jitter(width = 0.2, height = 0.2))
抖动使点仍然重叠,并且也将它们随机分布在给定区域上.
Jitter makes the dots still overlap and also distributes them to randomly on the given area.
是否有一种方法可以使点完全不重叠,而是尽可能紧密地聚集在一起,甚至可以相互接触,也不能并排"或堆叠?(以某种方式创建带有较小点的气泡)?
Is there a way to have the dots not overlapping at all, yet clustered as close together as possible, maybe even touching and also not "side by side" or stacked? (In a way, creating kind of bubbles with smaller dots)?
谢谢!
推荐答案
根据@Tjebo的建议,我在堆"中排列了点.
According to @Tjebo's suggestions I have arranged dots in "heaps".
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()
这篇关于抖动点无重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!