我有379838行和列(13个临床样品)13个变量的数据帧:
> str( df)
'data.frame': 379838 obs. of 13 variables:
$ V1 : num 0.8146 0.7433 0.0174 0.177 0 ...
$ V2 : num 0.7465 0.5833 0.0848 0.5899 0.0161 ...
$ V3 : num 0.788 0.843 0.333 0.801 0.156 ...
$ V4 : num 0.601 0.958 0.319 0.807 0.429 ...
$ V5 : num 0.792 0.49 0.341 0.865 1 ...
$ V6 : num 0.676 0.801 0.229 0.822 0.282 ...
$ V7 : num 0.783 0.732 0.223 0.653 0.507 ...
$ V8 : num 0.69 0.773 0.108 0.69 0.16 ...
$ V9 : num 0.4014 0.5959 0.0551 0.7578 0.2784 ...
$ V10: num 0.703 0.784 0.131 0.698 0.204 ...
$ V11: num 0.6731 0.8224 0.125 0.6021 0.0772 ...
$ V12: num 0.7889 0.7907 0.0881 0.7175 0.2392 ...
$ V13: num 0.6731 0.8221 0.0341 0.4059 0 ...
我试图做一个GGPLOT2箱线图分组变量分为三组:V1-V5,V6,V9和V10,V13和各组的变量分配不同的颜色。
我想下面的代码:
df1= as.vector(df[, c("V1", "V2", "V3","V4", "V5")])
df2= as.vector(df[, c("V6","V7", "V8","V9")])
df3=as.vector(df[, c( "V10","V11", "V12","V13")])
sample= c(df1,df2,df3)
library(reshape2)
meltData1 <- melt(df, varnames="sample")
str(meltData1)
'data.frame': 4937894 obs. of 2 variables:
$ variable: Factor w/ 13 levels "V1","V2","V3",..: 1 1 1 1 1 1 1 1 1 1 ...
$ value : num 0.8146 0.7433 0.0174 0.177 0 ...
p=ggplot(data=meltData1,aes(variable,value, fill=x$sample))
p+geom_boxplot()
这给了我白箱线图。 我怎样才能颜色分配到三组的变量? 提前谢谢了!
由于未提供的样本数据,由包含从名称13列的新的数据帧V1
至V13
。
df<-as.data.frame(matrix(rnorm(1300),ncol=13))
用函数melt()
从文库reshape2
数据被从宽转化为长格式。 现在,数据帧具有两列: variable
和value
。
library(reshape2)
dflong<-melt(df)
以长格式新列sample
添加。 在这里,我重复名称group1
, group2
, group3
,根据在原始数据帧,并且每个组中的原列数的行数。
dflong$sample<-c(rep("group1",nrow(df)*5),rep("group2",nrow(df)*4),rep("group3",nrow(df)*4))
新的列使用具有参数fill=
根据分组来设置颜色。
library(ggplot2)
ggplot(data=dflong,aes(variable,value, fill=sample))+geom_boxplot()
这是一个后续Didzis Elferts。
目的:与颜色组内的荫差拆分样品分成3个颜色组。
代码的第一部分是相同的:
df<-as.data.frame(matrix(rnorm(1300),ncol=13))
library(reshape2)
dflong<-melt(df)
dflong$sample<-c(rep("group1",nrow(df)*5),rep("group2",nrow(df)*4),rep("group3",nrow(df)*4))
library(ggplot2)
现在,使用包RColorBrewer选择色调
library(RColorBrewer)
创建彩色类的颜色列表
col.g <- c(brewer.pal(9,"Greens"))[5:9] # select 5 colors from class Greens
col.r <- c(brewer.pal(9,"Reds"))[6:9] # select 4 colors from class Reds
col.b <- c(brewer.pal(9,"Blues"))[6:9] # select 4 colors from class Blues
my.cols <- c(col.g,col.r,col.b)
看看所选择的颜色:
image(1:13,1,as.matrix(1:13), col=my.cols, xlab="my palette", ylab="", xaxt="n", yaxt="n", bty="n")
而现在我们所创建的颜色绘制
ggplot(data=dflong,aes(variable,value,colour=variable))+geom_boxplot()+scale_colour_manual(values = my.cols)
在上述中,与彩色和scale_colour_manual命令,只有线着色。 下面,我们用填充和scale_fill_manual:
ggplot(data=dflong,aes(variable,value,fill=variable))+geom_boxplot()+scale_fill_manual(values = my.cols)
PS我是一个总的新手和学习[R自己。 我看到这个问题,就是适用的东西我刚学的机会。