ggplot2: Dodge points with categorical axis and overlaying points

Viewed 932

Consider the following graph

d1 = data.frame(x=LETTERS[1:2],y=c(1.9,2.3))
d2 = data.frame(x=LETTERS[1:2],y=c(1.9,3))

ggplot(d1, aes(x=x,y=y)) + geom_point(data=d1, color="red") + 
              geom_point(data=d2, color="blue")

enter image description here

The goal is to dodge the blue toward the right and the red dots toward the left. One way would be to merge the two data.frames

d1$category=1
d2$category=2
d = rbind(d1,d2)
d$category = as.factor(d$category)
ggplot(d, aes(x=x,y=y, color=category)) +
     geom_point(data=d, position=position_dodge(0.3)) + 
      scale_color_manual(values=c("red","blue"))

enter image description here

Is there a another solution (a solution that does not require merging the data.frames)?

1 Answers

You can use position_nudge():

library(ggplot2)

d1 <- data.frame(x = LETTERS[1:2], y = c(1.9, 2.3))
d2 <- data.frame(x = LETTERS[1:2], y = c(1.9, 3))

ggplot(d1, aes(x, y)) +
  geom_point(d1, color = "red", position = position_nudge(- 0.05)) +
  geom_point(d2, color = "blue", position = position_nudge(0.05))

enter image description here

Related