0

Hello I'm trying to plot two violinplots one on another. I found useful posts here and I prepared the following code:

nums <- c(rep(1,12),rep(2,32),rep(3,19))
type <- rep('violin_green',63)

df1 <- data.frame(nums=nums,type=type)

nums <- c(rep(1,3),rep(2,15),rep(3,45))
type <- rep('violin_blue',63)

df2 <- data.frame(nums=nums,type=type)

p <- ggplot(df1, aes(factor(type), nums))
p <- p + geom_violin(aes(colour = df1$type, fill='red'), alpha = 0.3, trim=F)
q <- p + geom_violin(aes(y = df2$nums, colour = df2$type, fill='deepskyblue1'), alpha = 0.3, trim=F)
q + theme_bw() + ggtitle('Test title') + xlab('Test x')

Which gives:

enter image description here

But I'd like to change colors for green and blue as in data frames: violin_green and violin_blue instead of these default colors. Changing fill = doesn't do anything except exchange of the colors of the violin borders.

I tried with scale_color_manual and scale_fill_manual:

p <- ggplot(df1, aes(factor(type), nums))
p <- p + geom_violin(aes(df1$type, colour='violin_green_color', fill='violin_green_fill'), alpha = 0.3, trim=F) + 
  scale_color_manual(name='',values=c(violin_green_color = 'darkgreen')) +
  scale_fill_manual(name='',values=c(violin_green_fill = 'green'))
p
q <- p + geom_violin(aes(y = df2$nums, colour = 'violin_blue_color', fill='violin_blue_fill'), alpha = 0.3, trim=F) +
  scale_color_manual(name='',values=c(violin_blue_color = 'darkblue')) +
  scale_fill_manual(name='',values=c(violin_blue_fill = 'blue'))
q + theme_bw() + ggtitle('Test title') + xlab('Test x')

The result is:

enter image description here

But I'm unable to plot second violinplot due to:

Scale for 'colour' is already present. Adding another scale for 'colour', which will replace the existing scale.
Scale for 'fill' is already present. Adding another scale for 'fill', which will replace the existing scale.

I'd like also to have nice simple legend on the right. Coudl you help me with this one?

Adamm
  • 2,150
  • 22
  • 30

1 Answers1

0

Ok, I think I got this!

p <- ggplot(df1, aes(factor(type), nums))
p <- p + geom_violin(aes(df1$type, colour = 'darkgreen', fill='green'), alpha = 0.3, trim=F)
q <- p + geom_violin(aes(y = df2$nums, colour = 'darkblue', fill='blue'), alpha = 0.3, trim=F)
q <- q + scale_colour_manual(name='',values=c('darkblue','darkgreen')) +
  scale_fill_manual(name='',values=c('blue','green'))
q + theme_bw() + ggtitle('Test title') + xlab('Test x')

enter image description here

Adamm
  • 2,150
  • 22
  • 30