繁体   English   中英

如何在R中从lapply创建的每个图上添加标题?

[英]How to add titles to each plot created from lapply in R?

我试图将变量名称(即x,y和z)添加为每个箱形图的标题:

   bpdf = data.frame(group=c("A","A","A","B","B","B","C","C","C"),
                   x=c(1,1,2,2,3,3,3,4,4),
                   y=c(7,5,2,9,7,6,3,1,2),
                   z=c(4,5,2,9,8,9,7,6,7))

    par(mfrow=c(1,3))
    lapply(bpdf[-1],function(x){
    y <- sort(tapply(x,bpdf$group,median),decreasing=TRUE)
    boxplot(x~factor(bpdf$group,levels=names(y)), 
            main=paste(colnames(bpdf[-1])))
    }) 

我在main电话中遗漏了一些东西(请为以前的帮助提供帮助)。

当前方法的问题在于,当循环遍历列(data.frame /列表项)时,列名本身会丢失,如下所示:

devnull <- lapply(bpdf[-1], print)
# [1] 1 1 2 2 3 3 3 4 4
# [1] 7 5 2 9 7 6 3 1 2
# [1] 4 5 2 9 8 9 7 6 7

因此,您不必遍历列,而可以遍历变量名:

par(mfrow = c(1, ncol(bpdf) - 1)

lapply(names(bpdf)[-1], function(var){
  x <- bpdf[[var]]
  y <- sort(tapply(x, bpdf$group, median), decreasing = TRUE)
  boxplot(x ~ factor(bpdf$group,levels=names(y)), main = var)
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM