1
votes

I have a matrix of 9 columns and I want to create a violin plot using ggplot2. I would like to have different colours for groups of three columns, basically increasing order of "grayness". How can I do this?

I have tried imputing lists of colours on the option "fill=" but it does not work. See my example below. At the moment, it indicates "gray80", but I want to be able to specify the colour for each violin plot, in order to be able to specify the colour for groups of 3.

library(ggplot2)
dat <- matrix(rnorm(100*9),ncol=9)

# Violin plots for columns
mat <- reshape2::melt(data.frame(dat), id.vars = NULL)
pp <- ggplot(mat, aes(x = variable, y = value)) + geom_violin(scale="width",adjust = 1,width = 0.5,fill = "gray80")
pp
1

1 Answers

3
votes

We can add a new column, called variable_grouping to your data, and then specify fill in aes:

mat <- reshape2::melt(data.frame(dat), id.vars = NULL)

mat$variable_grouping <- ifelse(mat$variable %in% c('X1', 'X2', 'X3'), 'g1',
                                   ifelse(mat$variable %in% c('X4','X5','X6'), 
                                         'g2', 'g3'))

ggplot(mat, aes(x = variable, y = value, fill = variable_grouping)) + 
    geom_violin(scale="width",adjust = 1,width = 0.5)

enter image description here

You can control the groupings using the ifelse statement. scale_fill_manual can be used to specify the different colors used to fill the violins.