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")
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"))
Is there a another solution (a solution that does not require merging the data.frames)?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With