R: How to spread (jitter) points with respect to the x axis?

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)

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

Tags:

R

Ggplot2

Jitter