ggplot小提琴情节,按组指定不同的颜色? [英] ggplot violin plot, specify different colours by group?

查看:671
本文介绍了ggplot小提琴情节,按组指定不同的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个9列的矩阵,我想使用ggplot2创建一个小提琴图.我希望三列的组具有不同的颜色,基本上增加了灰色"的顺序.我该怎么办?

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?

我尝试在选项"fill ="上插入颜色列表,但是它不起作用.请参阅下面的示例.目前,它指示为"gray80",但是我希望能够为每个小提琴图指定颜色,以便能够为3个组指定颜色.

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

推荐答案

我们可以在数据中添加一个名为variable_grouping的新列,然后在aes中指定fill:

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)

您可以使用ifelse语句控制分组. scale_fill_manual 可用于指定用于填充小提琴的不同颜色.

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.

这篇关于ggplot小提琴情节,按组指定不同的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆