ggplot violin plot, specify different colours by group?

巧了我就是萌 提交于 2019-12-11 08:54:32

问题


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:


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)

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.



来源:https://stackoverflow.com/questions/50645517/ggplot-violin-plot-specify-different-colours-by-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!