Search code examples
rggplot2legendviolin-plot

Solid color legend for split violin plot (ggplot)?


I'm trying to get the legend colors in this split violin plot to be solid. I've successfully removed the lines that were here (following a different post on this site), but I can't figure out how to proceed.

split violins

ctn_sv <- ggplot(z, aes(x = time, y = ctn_mean, fill = group), position = position_dodge(.9), alpha = .01) + 
  geom_split_violin(trim = TRUE, alpha = 0.65) +
  ggtitle("CTN: FFF vs ZZZ")+
  theme_bw() + theme(legend.title = element_blank()) +
  scale_fill_brewer(palette = "Dark2") +
  stat_summary(fun = mean, fun.min = mean, fun.max = mean,
               geom = "crossbar", 
               width = 0.25,
               position = position_dodge(width = .25)) +
  guides(fill = guide_legend(override.aes = list(linetype = 0)),
         color = guide_legend(override.aes = list(linetype = 0)))

I used the code for split violin plot from here Split violin plot with ggplot2

Thanks in advance for any advice!


Solution

  • Your geom="crossbar" is giving you that issue. You can use show.legend=FALSE in stat_summary to resolve this. See below code and corresponding output:

    set.seed(20160229)
    
    z = data.frame(
      y=c(rnorm(1000), rnorm(1000, 0.5), rnorm(1000, 1), rnorm(1000, 1.5)),
      x=c(rep('a', 2000), rep('b', 2000)),
      group=c(rep('i', 1000), rep('j', 2000), rep('i', 1000))
    )
    
    ctn_sv <- ggplot(z, aes(x = x, y = y, fill = group), position = position_dodge(.9), alpha = .71) + 
      geom_split_violin(trim = TRUE, alpha = 0.65) +
      ggtitle("CTN: FFF vs ZZZ")+
      theme_bw() + 
      theme(legend.title = element_blank()) +
      scale_fill_brewer(palette = "Dark2") +
      stat_summary(fun = mean, fun.min = mean, fun.max = mean,
                   geom = "crossbar", 
                   width = 0.25,
                   show.legend = FALSE,
                   position = position_dodge(width = .25)) 
    ctn_sv
    

    output