且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-26 23:49:40

另一个仅用于横向的选项是指定 position_dodge 并将其传递给位置$ c

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


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:

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

Another option for horizontal only would be to specify position_dodge and pass this to the position argument for each geom.

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