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

标签 r plot 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)

创建函数以生成绘图:

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)

使用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

最佳答案

我建议使用 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>

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

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

保存它们
walk2(by_type$type, by_type$plot, 
      ~ggsave(paste0(.x, ".pdf"), .y))

enter image description here

关于r - 通过 for 循环/lappy 对数据进行子集化和绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48527446/

相关文章:

r - 在 R 中按组创建连续年份的计数

R:将字符串作为参数传递时没有引号

r - 为 facet_wrap (ggplot2) 中的每个图指定不同的 xlim

r - 在 ggplot2 中绘制带空格的分箱离散数据

plot - 使用 gnuplot 的迭代参数图

删除 PNG 图边距

r - 温度图 : Error in FUN(X[[i]], ...) : 未找到对象 'y'

r - 从plot3d绘图中保存3D图形应用程序的文件

r - 在 ggplot2 中插入图像作为构面

r - 在 "for"循环中绘制几张不同大小的图片