18

I have a ggplot2 linegraph with two lines featuring significant overlap. I'm trying to use position_jitterdodge() so that they are more visible, but I can't get the lines and points to both jitter in the same way. I'm trying to jitter the points and line horizontally only (as I don't want to suggest any change on the y-axis). Here is an 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")

Which produces the ugly:

Line/point mismatch

I've obviously got something fundamentally wrong here: What should I do to make the geom_point jitter follow the geom_line jitter?

4

3 回答 3

21

仅水平的另一个选项是指定position_dodge并将其传递给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")

在此处输入图像描述

于 2016-09-16T14:25:26.353 回答
15

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

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

在此处输入图像描述

您的离散 X 轴的水平解决方案并不那么干净(当 ggplot2 执行此操作时,它在幕后是干净,因为它可以很好地为您处理轴和点转换)但它是可行的:

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

在此处输入图像描述

于 2016-09-16T14:07:59.200 回答
4

2017 年 7 月,开发ggplot2者添加了seed关于position_jitter函数的参数(https://github.com/tidyverse/ggplot2/pull/1996)。

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

请注意,此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")

在此处输入图像描述

于 2020-03-10T11:16:13.853 回答