Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
878 views
in Technique[技术] by (71.8m points)

r - How to jitter both geom_line and geom_point by the same magnitude?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...