首页 > 解决方案 > 如何使用 geom_segments 进行抖动

问题描述

我在 ggplot 中使用 geom_segments 链接了两个点。它适用于 geom_pointgeom_point 已链接但是当我使用 geom_jitter 它并没有给我想要的结果使用抖动的结果。我想查看它们之间的所有点。你能帮我如何使用geom_jitter连接点吗?为什么点看起来不平行?

我根据建议修改了代码,现在点位置已更改点位置已更改

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)

标签: rggplot2jitter

解决方案


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

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))

在此处输入图像描述

现在知道这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))

在此处输入图像描述

正如你所看到的,这看起来很可怕,因为每个点都是独立于其他点抖动的。我们可以通过设置抖动的种子来更接近我们想要的:

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))

在此处输入图像描述

这现在按预期处理左侧点(因为种子应该对每个点进行相同的随机过程),但会弄乱右侧点。发生这种情况是因为这些与左点同时抖动为后续数字,而不是与左点平行。

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

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))

在此处输入图像描述


推荐阅读