我有一个ggplot,其中一些点与其他一些点重叠。我想知道是否有办法将这些要点放在另一个之上。就我而言,最多有2个点重叠。
x=c(1,1,2,3,4,4)
y=c('a1','a1','a2','a3','a4','a4')
type = c('A','B','C','A','B','C')
data = as.data.frame(cbind(x,y,type))
ggplot() + geom_point(data = data, aes(x=x,y=y, color = type, fill = type), size = 2, shape = 25)
Run Code Online (Sandbox Code Playgroud)
在这里,我们看到,点x=1 and y=a1的type A是坐在下面type B,但我非常希望Type B可以通过位垂直移动。
如果使用抖动,则所有事物都会移位,包括没有重叠的点。
我们可以使用duplicated或任何类似的函数来检测重叠,然后可以使用R索引jitter来选择性地应用抖动。
我把它写成一个函数:
selective_jitter <- function(x, # x = x co-ordinate
y, # y = y co-ordinate
g # g = group
){
x <- as.numeric(x)
y <- as.numeric(y)
a <- cbind(x, y)
a[duplicated(a)] <- jitter(a[duplicated(a)], amount = .15) # amount could be made a parameter
final <- cbind(a, g)
return(final)
}
data <- as.data.frame(selective_jitter(data$x, data$y, data$type))
ggplot() + geom_point(data = data, aes(x=x,y=y, color = g, fill = type), size = 2, shape = 25)
Run Code Online (Sandbox Code Playgroud)
有很多方法可以不同地编写或调整它。例如,我认为一个很好的调整是为的amount选项添加一个可选参数jitter()。
另一个潜在的改进是使用游标卡尺查找(近)重复项和精确重复项(而duplicated只是查找精确重复项)。
最后说明-有时我这样做时喜欢使用半透明颜色而不是jitter。仅当序列(type)的数量少时,此变体才能很好地起作用,以便您可以执行以下操作:黄色显示1个序列,蓝色显示1个序列,然后它们的重叠将变为绿色(Stack Overflow上存在现有解决方案),从而证明如果您有兴趣。