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)
答案 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))
现在,可能很容易知道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))