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!

2

Best Answer


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

You could use geom_jitter like this:

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)library(ggplot2)ggplot(data, aes(exp, result, fill=time)) + geom_boxplot() +geom_jitter()

Created on 2022-08-30 with reprex v2.0.2