7

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?

Poiu Rewq
  • 182
  • 13

2 Answers2

8

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)

enter image description here

Marco Sandri
  • 23,289
  • 7
  • 54
  • 58
  • which ggplot version do you use? I have following error with `ggplot2_2.2.1`: `Error in layer(data = data, mapping = mapping, stat = stat, geom = GeomViolin, : object 'dodge' not found` – Roman Mar 23 '18 at 14:20
  • I have tried it. But then the plot looks not as expected. Using `position = position_dodge(width = 1)` was successfull....strange – Roman Mar 23 '18 at 14:26
  • 2
    @Jimbou, you got this error because you didn't set `dodge <- position_dodge(width = 1)` – Poiu Rewq Mar 23 '18 at 15:34
2

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)

enter image description here

Roman
  • 17,008
  • 3
  • 36
  • 49
  • That's the exact opposite of what I've wanted. Marco provided answer which suits the best. Notice the use of `interaction()` – Poiu Rewq Mar 23 '18 at 15:33
  • @PoiuRewq I tried to avoid the interaction. See my edits. It is also possible to get white boxes using this appoach. – Roman Mar 27 '18 at 12:55