21

I have the following code snippet in R:

dat <- data.frame(cond = factor(rep("A",10)), 
                  rating = c(1,2,3,4,6,6,7,8,9,10))
ggplot(dat, aes(x=cond, y=rating)) +
  geom_boxplot() + 
  guides(fill=FALSE) +
  geom_point(aes(y=3)) +
  geom_point(aes(y=3)) +
  geom_point(aes(y=5))

This particular snippet of code produces a boxplot where one point goes over another (in the above case one point 3 goes over another point 3).

How can I move the point 3 so that the point remains in the same position on the y axis, but it is slightly moved left or right on the x axis?

chao
  • 1,893
  • 2
  • 23
  • 27

3 Answers3

31

This can be achieved by using the position_jitter function:

geom_point(aes(y=3), position = position_jitter(w = 0.1, h = 0))

Update: To only plot the three supplied points you can construct a new dataset and plot that:

points_dat <- data.frame(cond = factor(rep("A", 3)), rating = c(3, 3, 5))                  
ggplot(dat, aes(x=cond, y=rating)) +
  geom_boxplot() + 
  guides(fill=FALSE) +
  geom_point(aes(x=cond, y=rating), data = points_dat, position = position_jitter(w = 0.05, h = 0)) 
Lars Lau Raket
  • 1,905
  • 20
  • 35
  • many thanks for the quick response. Yes, at one point I tried that as well. The problem is that when I use jitter function it plots many points. So in my example I have three dots, two on the position 3, but when I add position_jitter it plots more than 10 points. Do you have any idea why? – chao Jul 14 '15 at 12:09
  • Exactly what I needed! Thanks! – chao Jul 14 '15 at 12:21
7

ggplot2 now includes position_dodge(). From the help's description: "Dodging preserves the vertical position of an geom while adjusting the horizontal position."

Thus you can either use it as geom_point(position = position_dodge(0.5)) or, if you want to dodge points that are connected by lines and need the dodge to the be the same across both geoms, you can use something like:

dat <- data.frame(cond = rep(c("A", "B"), each=10), x=rep(1:10, 2), y=rnorm(20))
dodge <- position_dodge(.3) # how much jitter on the x-axis?
ggplot(dat, aes(x, y, group=cond, color=cond)) + 
  geom_line(position = dodge) + 
  geom_point(position = dodge)
Florian
  • 579
  • 1
  • 10
  • 19
1

ggplot2 now has a separate geom for this called geom_jitter so you don't need the position = dodge or position = position_dodge()) argument. Here applied to OP's example:

dat <- data.frame(cond = factor(rep("A",10)), 
                  rating = c(1,2,3,4,6,6,7,8,9,10))
ggplot(dat, aes(x=cond, y=rating)) +
  geom_boxplot() + 
  guides(fill=FALSE) +
  geom_jitter(aes(y=c(3, 3, 5)))
Andrew
  • 490
  • 3
  • 9