0

I am trying to plot overlaying violin plots by condition within the same variable.

Var <- rnorm(100,50)
Cond <- rbinom(100, 1, 0.5)
df2 <- data.frame(Var,Cond)

ggplot(df2)+
  aes(x=factor(Cond),y=Var, colour = Cond)+
  geom_violin(alpha=0.3,position="identity")+
  coord_flip()

So, where do I specify that I want them to overlap? Preferably, I want them to become more lighter when overlapping and darker colour when not so that their differences are clear. Any clues?

  • You might check out: https://stackoverflow.com/questions/19483074/overlay-violin-plots-ggplot2 – harre Jul 14 '22 at 14:05
  • Yes, I've looked at it, but they use two variables and overlap them. I have one variables split into two by another variabler. It's not quite the same. – Andreas Massey Jul 14 '22 at 14:12

1 Answers1

2

If you don't want them to have different (flipped) x-values, set x to a constant instead of x = factor(Cond). And if you want them filled in, set a fill aesthetic.

ggplot(df2)+
  aes(x=0,y=Var, colour = Cond, fill = Cond)+
  geom_violin(alpha=0.3,position="identity")+
  coord_flip()

enter image description here

coord_flip isn't often needed anymore--since version 3.3.0 (released in early 2020) all geoms can point in either direction. I'd recommend simplifying as below for a similar result.

df2$Cond = factor(df2$Cond)
ggplot(df2) +
  aes(y = 0, x = Var, colour = Cond, fill = Cond) +
  geom_violin(alpha = 0.3, position = "identity")
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294