elisa
elisa

Reputation: 995

Combine spaghetti plot (with a grouping variable) with split-violins (without it) in ggplot2

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)

Upvotes: 4

Views: 1073

Answers (1)

Djork
Djork

Reputation: 3369

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

Upvotes: 3

Related Questions