通过 for 循环 / lappy 对数据进行子集和绘图

may*_*cca 2 plot r ggplot2

我有大约 300 个站点位于多个山脉类型。我正在尝试制作一些有意义的情节。因此,我想按山地类型(类型)对我的数据进行子集化,并通过 ggplot2 对其进行绘制。我想通过 for 循环或 lapply 自动化该过程,但我是两者的初学者。

我发现了一些使用 for 循环的好例子:http : //www.reed.edu/data-at-reed/resources/R/loops_with_ggplot2.html 或使用 lapply: Use for loop in ggplot2 to generate a list

但是,这两种方法都会生成空图。我究竟做错了什么?我该如何修复我的代码?

# Create dummy data
df<- data.frame(loc = rep(c("l1", "l2"), each = 3),
                name = rep(c("A", "B"), 3),
                grid = c(5,6,7,2,3,5),
                area = c(5,10,1,1,3,1),
                areaOrig = rep(c(20, 10, 5), each = 2))

df2<-rbind(df, df)

# Create two mountain types types
df2$type = rep(c("y", "z"), each = 6)
Run Code Online (Sandbox Code Playgroud)

创建function以生成图:

require(ggplot2)

type.graph <- function(df2, na.rm = TRUE, ...) {

  # Create list of locations
  type_list <-unique(df2$type)

  # Create a for loop to produce ggpot plots
  for (i in seq_along(type_list)) {

    # create a plot for each loc in df
    plot<-

      windows()

      ggplot(subset(df2, df2$type == type_list[i]),
             aes(x = grid, 
                 y = area)) +
        geom_bar(stat = "identity") +
        ggtitle(type_list[i]) +
        facet_grid(loc ~name)

    print(plot)
  }
}

type.graph(df2)
Run Code Online (Sandbox Code Playgroud)

使用lapply以生产图:

#significant SNPs
type_list <- unique(df2$type)

#create list of ggplots per type
p_re <-
  lapply(type_list, function(i){

    ggplot(subset(df2, type == type_list[i]), 
           aes(x = grid, 
               y = area)) +
      geom_bar(stat = "identity")

  })

#assign names
names(p_re) <- type_list

#plot
p_re$y
Run Code Online (Sandbox Code Playgroud)

Dan*_*son 5

我建议使用 purrr 包作为 tidyverse 的一部分,通过分组因子嵌套数据框,然后循环遍历子集数据。下面是一个例子:

library(tidyverse)

by_type <- df2 %>% 
  group_by(type) %>% 
  nest() %>% 
  mutate(plot = map(data, 
                    ~ggplot(. ,aes(x = grid, y = area)) +
                      geom_bar(stat = "identity") +
                      ggtitle(.) +
                      facet_grid(loc ~name)))

by_type
# A tibble: 2 x 3
  type  data             plot    
  <chr> <list>           <list>  
1 y     <tibble [6 × 5]> <S3: gg>
2 z     <tibble [6 × 5]> <S3: gg>
Run Code Online (Sandbox Code Playgroud)

以上为您提供了一个普通的数据框,但数据和绘图列是列表列。因此,数据的第一个“单元格”包含所有数据,type == y第二个包含所有数据type == z。这个基本结构是由tidyr::nest. 然后,您通过使用 循环遍历数据列表列来创建一个新变量,我称之为 plot,purrr::map您只需要将 data 参数替换为.。请注意,当您想要一次遍历多个内容时,有map2pmap函数(例如,如果您希望标题有所不同。

然后,您可以使用 轻松查看您的数据by_type$plot,或使用

walk2(by_type$type, by_type$plot, 
      ~ggsave(paste0(.x, ".pdf"), .y))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明