如何使用geom_segments进行抖动

时间:2019-11-10 21:53:44

标签: r ggplot2 jitter

我在ggplot中使用geom_segments链接了两点。它对于geom_point geom_point are linked效果很好,但是当我使用geom_jitter时,它并没有给我想要的结果outcome using jitter。我想查看所有点,并在两个点之间有一条线。您能帮我如何使用geom_jitter连接点吗?为什么点看起来不平行?

我根据建议修改了代码,现在点的位置已更改points position has been changed

ggplot() +  
geom_point(data = mydata, aes(x = lower, y = lower_p)) + 
geom_point(data = mydata, aes(x = higher, y = higher_p)) + 

geom_segment(aes(x = lower, y = ifelse(lower_p!= higher_p, NA, lower_p), xend = higher, yend = 
higher_p), data = mydata)

1 个答案:

答案 0 :(得分:2)

由于没有发布示例数据,因此我使用一些虚拟数据来说明一些事情。让我们进行设置:

df <- data.frame(x = c(1,1,1,2,2),
                 xend = c(2,2,2,3,3),
                 y = c(1,1,1,2,2),
                 yend = c(1,1,1,2,2))

如果我们绘制的图形与您发布的图形相似,则会得到以下图形,其中点被重复绘制了2-3次:

ggplot(df) +
  geom_point(aes(x, y), colour = "red") +
  geom_point(aes(xend, yend), colour = "dodgerblue") +
  geom_segment(aes(x = x, y = y, xend = xend, yend = yend))

enter image description here

现在,可能很容易知道geom_jitter()geom_point(position = "jitter")的简写。像大多数职位一样,您可以给position_jitter()自变量指定希望如何发生抖动。例如,我们可能只想在y方向上抖动:

ggplot(df) +
  geom_point(aes(x, y), colour = "red", 
             position = position_jitter(height = 0.1, width = 0)) +
  geom_point(aes(xend, yend), colour = "dodgerblue",
             position = position_jitter(height = 0.1, width = 0)) +
  geom_segment(aes(x = x, y = y, xend = xend, yend = yend),
               position = position_jitter(height = 0.1, width = 0))

enter image description here

如您所见,这看起来太可怕了,因为每个点都独立于每个其他点抖动。通过设置抖动种子,我们可以更接近我们想要的东西:

ggplot(df) +
  geom_point(aes(x, y), colour = "red", 
             position = position_jitter(height = 0.1, width = 0, seed = 1)) +
  geom_point(aes(xend, yend), colour = "dodgerblue",
             position = position_jitter(height = 0.1, width = 0, seed = 1)) +
  geom_segment(aes(x = x, y = y, xend = xend, yend = yend),
               position = position_jitter(height = 0.1, width = 0, seed = 1))

enter image description here

这现在可以按预期方式处理左边的点(因为种子应该对每个点都进行相同的随机处理),但是弄​​乱了右边的点。之所以会发生这种情况,是因为这些信号与左点同时作为后续数字抖动,而不是平行于左点。

唯一合理的解决方案似乎是预先计算抖动,并使用该抖动以使每个点都相同:

set.seed(0)
df$jit <- runif(nrow(df), -0.05, 0.05)

ggplot(df) +
  geom_point(aes(x, y + jit), colour = "red") +
  geom_point(aes(xend, yend + jit), colour = "dodgerblue") +
  geom_segment(aes(x = x, y = y + jit, xend = xend, yend = yend + jit))

enter image description here