2

我正在尝试将 ggplot2 图添加到列表中,以便我可以使用 ggpubr 中的 ggarrange 函数将它们组织在多个页面上。

由于有数百个图,我正在使用一个函数来生成和保存图,但我无法让它将图返回到环境或将名称写入列表。

我相当确定这是我遗漏但无法发现的简单事物。

我正在使用的绘图功能是:

histFacet.plot <- function(x, results, info, ...) {

  md<- names(x) %in% c("rn","Taxa","year","rep","block","column",
                       "range", "entity_id")
  traits <- names(x[ , !md])
  for (i in traits) {
    i <-ggplot(data = x, aes_string(x = i)) + 
      geom_histogram(colour="black", fill="white") + 
      #facet_grid(x$year ~ .) +
      theme_bw() +
      xlab(paste0(i)) +
      ylab("Frequency") +
      theme(panel.grid.major = element_blank()) +
      theme(panel.grid.minor = element_blank()) +
      theme(axis.text = element_text(size = 15)) +
      theme(axis.title = element_text(size = 15)) +
      theme(strip.text = element_text(size = 15)) 
    #ggsave(paste0(i,"_",info,".pdf"),path=paste(results, sep=''))
    plotList<- list(plotList, list(i))
    print(i)

  }
  return(i)
}

histFacet.plot(pd,'~/Dropbox/Research_Poland_Lab/AM Panel/Figures/Hist/',
               "_raw_2018")
4

1 回答 1

0

你的大问题是你return(i)而不是return(plotList). 在迭代器中使用 as 在循环i内重新分配很奇怪。特别是当情节用作字符串时......我会试试这个:forii

histFacet.plot <- function(x, results, info, ...) {

  md <- names(x) %in% c("rn","Taxa","year","rep","block","column",
                       "range", "entity_id")
  traits <- names(x[ , !md])
    plotList = list()
    for (i in traits) {
        thisPlot <- ggplot(data = x, aes_string(x = i)) + 
          geom_histogram(colour="black", fill="white") + 
          #facet_grid(x$year ~ .) +
          theme_bw() +
          xlab(i) +
          ylab("Frequency") +
          theme(panel.grid.major = element_blank()) +
          theme(panel.grid.minor = element_blank()) +
          theme(axis.text = element_text(size = 15)) +
          theme(axis.title = element_text(size = 15)) +
          theme(strip.text = element_text(size = 15)) 

        plotList[[i]] = thisPlot
        print(i)

      }
      return(plotList)
}

当然,未经测试,因为您没有共享示例数据。如果您提供一个小的、可重复的示例数据集,那么很高兴测试/调试。

我不确定您是否要将print(i)绘图打印到图形设备(如果是,请更改为print(thisPlot))或将当前特征打印到控制台以通过循环更新进度(如果是,请更改为message(i)以便于禁用)。

其他几点注意事项:如果您分面,请year ~ .用作公式,而不是x$year ~ .. 如果i已经是一个字符,则paste0(i)i(in your xlab) 相同。

于 2018-12-03T17:40:35.657 回答