rggplot2reshape2melt

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

Said plot

Can I make only boxplots white and not violins?

P.S. How can I make legends only for violins and not showing boxplots?


Solution

  • Try this:

    dodge <- position_dodge(width = 1)
    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)
    

    enter image description here