简体   繁体   中英

R Violin plots and boxplots together, make fill behave differently only for boxplots

Ok, so I want to plot violin plots together with white boxplots, but my data is a little bit tricky. I melted data from data.frame with several columns, each of which has values corresponding to factor with two levels, here is approximation of my data:

library(ggplot2)
library(reshape2)

dat <- list(
  A = rbind(
    data.frame(group = "1",
               vals = rnorm(500)),
    data.frame(group = "2",
               vals = rnorm(100))
  ),
  B = rbind(
    data.frame(group = "1",
               vals = rnorm(500)),
    data.frame(group = "2",
               vals = rnorm(100))
  ),
  C = rbind(
    data.frame(group = "1",
               vals = rnorm(500)),
    data.frame(group = "2",
               vals = rnorm(100))
  )
)

dat.melt <- melt(dat)

The best I could find is to set fill manually, but it affects both violin plots and boxplots:

dodge <- position_dodge(width = 1)

p <- ggplot(dat.melt, aes(x = L1, y = value, fill = group))+
  geom_violin(position = dodge)+
  geom_boxplot(width = 0.3,
                 position = dodge,
                 outlier.shape = NA)+
  scale_fill_manual(values=c("white", "white"))

说情节

Can I make only boxplots white and not violins?

PS How can I make legends only for violins and not showing boxplots?

Try this:

p <- ggplot(dat.melt, aes(x = L1, y = value)) +
  geom_violin(aes(fill = group), position = dodge) +
  geom_boxplot(aes(group=interaction(group,L1)), 
            width=0.3, fill="white", position=dodge,
            outlier.shape=NA)
print(p)

在此输入图像描述

You can also try this:

ggplot(dat.melt, aes(x = L1, y = value, fill=group))+
  geom_violin(position = position_dodge(width = 1)) +
  geom_boxplot(data = dat.melt, 
               aes(x = L1, y = value, col=group), fill="white", 
               position = position_dodge(width = 1), width=0.3,outlier.shape=NA)+
  geom_boxplot(position = position_dodge(width = 1), alpha=0, width=0.3)

在此输入图像描述

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