4

Here's a minimal reproducible example:

library(ggplot2)


mydata <- data.frame(condition = c(rep("One",40), rep("Two",40)),
                     participant = rep(1:40,2),
                     observation = c(rnorm(40,2,1), rnorm(40,0,1)))

#my.plot <- ggplot(mydata, aes(x=condition, y=observation, group=participant)) +
my.plot <- ggplot(mydata, aes(x=condition, y=observation)) +
  geom_point(size=3) +
  geom_line(size=1, alpha=0.5) +
  xlab('condition') +
  ylab('Observation') 

dataDensity <- mydata %>%
  group_by(condition) %>%
  do(data.frame(loc = density(.$observation)$x,
                dens = density(.$observation)$y,
                participant=1))

dataDensity$dens <- ifelse(dataDensity$condition == "One", .9+(dataDensity$dens * -1), 2.1+(dataDensity$dens))
my.plot + geom_polygon(data = dataDensity, aes(dens, loc, fill = condition))

This gives me the following plot: enter image description here

Which is close to what I want, but not quite. I actually want to group each corresponding pair of points between conditions "One" and "Two". So when I add the grouping variable (as I do with the line commented out in the snippet above) I get this problem:

enter image description here

Which is interesting, but not what I'm after.

I had to add the hack/workaround participant=1 to prevent the error message:

Error in FUN(X[[i]], ...) : object 'participant' not found

How can I combine the scattered points with a grouping variable but keep the split violins independent?

(NOTE: the vertical line in the first plot is just because I have the geom_line)

markus
  • 25,843
  • 5
  • 39
  • 58
elisa
  • 965
  • 9
  • 27
  • 2
    Each `geom` can have their own `aes`. Thus, move relevant parts of `aes` (i.e. `group = participant`) from the top level in `ggplot` to `geom_line`. – Henrik Jun 13 '19 at 21:53
  • See **Details** section in `?ggplot` – Henrik Jun 13 '19 at 22:03

1 Answers1

3

A solution is to restrict the group aesthetics to only the geom_line layer. When you provide aesthetic mapping within the parent ggplot() call, all additional layers inherit those aesthetics.

my.plot2 <- ggplot(mydata, aes(x=condition, y=observation)) +
  geom_point(size=3) +
  geom_line(aes(group=participant), size=1, alpha=0.5) +
  xlab('condition') +
  ylab('Observation') 

my.plot2 + geom_polygon(data = dataDensity, aes(dens, loc, fill = condition))

enter image description here

Djork
  • 3,319
  • 1
  • 16
  • 27