R:如何在ggplot2 linegraph中抖动geom_line和geom_point?

时间:2016-09-16 14:02:30

标签: r ggplot2 jitter

我有一个ggplot2线图,其中两行显着重叠。我尝试使用position_jitterdodge()以便它们更加明显,但我无法以相同的方式获得线条和指向两者的抖动。我试图只是水平抖动点和线(因为我不想在y轴上建议任何变化)。这是一个MWE:

## Create data frames
dimension <- factor(c("A", "B", "C", "D"))
df <- data.frame("dimension" = rep(dimension, 2),
                 "value" = c(20, 21, 34, 32,
                             20, 21, 36, 29),
                 "Time" = c(rep("First", 4), rep("Second", 4)))
## Plot it
ggplot(data = df, aes(x = dimension, y = value,
                      shape = Time, linetype = Time, group = Time)) +
    geom_line(position = position_jitterdodge(dodge.width = 0.45)) +
    geom_point(position = position_jitterdodge(dodge.width = 0.45)) +
    xlab("Dimension") + ylab("Value")

产生丑陋的东西:

Line/point mismatch

我显然在这里遇到了一些根本性错误:我应该怎样做才能使geom_point抖动跟随geom_line抖动?

3 个答案:

答案 0 :(得分:14)

仅横向的另一个选项是指定position_dodge并将其传递给每个geom的position参数。

pd <- position_dodge(0.4)

ggplot(data = df, aes(x = dimension, y = value,
                      shape = Time, linetype = Time, group = Time)) +
  geom_line(position = pd) +
  geom_point(position = pd) +
  xlab("Dimension") + ylab("Value")

enter image description here

答案 1 :(得分:12)

一种解决方案是手动抖动点:

df$value_j <- jitter(df$value)

ggplot(df, aes(dimension, value_j, shape=Time, linetype=Time, group=Time)) +
  geom_line() +
  geom_point() +
  labs(x="Dimension", y="Value")

enter image description here

你的离散X轴的水平解决方案并不干净(当ggplot2完成时它是干净的under the covers,因为它很好地处理了你的轴和点转换)但它是可行的:

df$dim_j <- jitter(as.numeric(factor(df$dimension)))

ggplot(df, aes(dim_j, value, shape=Time, linetype=Time, group=Time)) +
  geom_line() +
  geom_point() +
  scale_x_continuous(labels=dimension) +
  labs(x="Dimension", y="Value")

enter image description here

答案 2 :(得分:3)

2017年7月,ggplot2的开发人员在seed函数(https://github.com/tidyverse/ggplot2/pull/1996)上添加了position_jitter自变量。

因此,现在(这里:ggplot2 3.2.1),您可以将参数seed传递给position_jitter,以便在jitter中具有相同的geom_point效果,并且geom_line(请参阅官方文档:https://ggplot2.tidyverse.org/reference/position_jitter.html

请注意,此seed自变量在geom_jitter中尚不存在。

ggplot(data = df, aes(x = dimension, y = value,
                      shape = Time, linetype = Time, group = Time)) +
  geom_line(position = position_jitter(width = 0.25, seed = 123)) +
  geom_point(position = position_jitter(width = 0.25, seed = 123)) +
  xlab("Dimension") + ylab("Value")

enter image description here