aes_string有颜色的审美

时间:2017-06-28 07:10:55

标签: r ggplot2 aesthetics

要获得一个包含2个ggplot对象的列表,我的函数gscatFn2如下所示。 而不是使用列名"周"对于数据框,我想使用列索引7进行美学映射,如下所示。但错误信息:

Error in sort.list(y) : 'x' must be atomic for 'sort.list'Have you called 'sort' on a list?

我的颜色美学映射必定存在问题,我无法弄清楚。

df1 <- data.frame(list(Avg=c(0.282,0.282,0.282,0.733),CV=c(0.7,1.06,0.7,0.9),Lot=c("a","b","c","d"),Model=c("m1","m2","m3","m4"),Size=c("01","02","03","04"),Month=c("11","11","22","22"),Week=c("23","23","24","24")))
df2 <- data.frame(list(Avg=c(0.010,0.02,0.029,0.083),CV=c(0.04,0.9,0.4,0.1),Lot=c("a","b","c","d"),Model=c("m1","m2","m3","m4"),Size=c("01","02","03","04"),Month=c("11","11","22","22"),Week=c("23","23","24","24")))

grp2 <- list(df1, df2) 

gscatFn2 <- function(grp, ccc, ccv,  cca, cccol) {
#grp: 2 data frame, ccc: Size, ccv : CV, cca : Avg, cccol : Week 
#ggpplot object for each data frame shall return
library(ggplot2)
p <- list()
for (i in ( 1:length(grp) ) )  {
#for each data frame repeat
    #x and y
    p1 <- ggplot(grp[[i]], aes_string( x=colnames(grp[[i]])[cca],y=colnames(grp[[i]])[ccv] )) 
    #color
    p2 <- p1 +  geom_point(aes_string( color= colnames(factor(grp[[i]])[cccol])  ) ) + scale_color_manual(values= c("deepskyblue3","firebrick"))
    #accumulate
    p[[i]] <- p2
}
return(p)
}

# for testing   
pp <- gscatFn2(grp2,5,2,1,7)  # <<<- I got error "Error in sort.list(y) : 'x' must be atomic..."
print(pp[[1]])

1 个答案:

答案 0 :(得分:0)

除了构建图表的奇怪方式之外,我不会说话 - 你可能有充分的理由去做 - 我看到的唯一问题是使用

colnames(factor(grp[[i]])[cccol])))

将其更改为

 colnames(grp[[i]])[cccol]))

解决了这个问题:

MSDN