简体   繁体   中英

Overlay violin plots in r

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?

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()

在此处输入图像描述

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM