rggplot2boxplotscatter

Stacked boxplot and scatter plot - group BOTH by same variable


I am trying to create a scatter plot stacked on a boxplot. Similar dummy data below. The boxplot behaves well, as I want one boxplot for each of the three "exp" variables both "before" AND "after" (as seen in graph below, 6 box plots).

The problem however is that I also want the scatter plot data to lie on top of the correct plot (divided by before/after). Now, the points are just in between the two box plots, as you can see.

exp <- rep(c("smile", "neutral", "depressor"), each=5, times=2)
time <- rep(c("before", "after"), each = 15)
result <- rnorm(15, mean=50, sd=4)
result <- append(result, c(rnorm(15, mean=47, sd=3)))
data <- data.frame(exp, time, result)

ggplot(data, aes(exp, result, fill=time)) + 
  geom_boxplot() +
  geom_point()

I would really appreciate some input, thanks in advance!


Solution

  • Is this solving your issue?
    Here you add the time group in geom_point.

    ggplot(data, aes(exp, result, fill=time)) +
      stat_boxplot(width=0.5, position = position_dodge(1)) +
      geom_boxplot(position = position_dodge(1), outlier.shape = NA)+
      geom_point(aes(fill = time, group = time), color="black", 
                 position = position_jitterdodge(jitter.width = .1, dodge.width = 1))
    

    Before

    enter image description here

    After

    enter image description here