【问题标题】:Subset and plot data by for loop / lappy通过 for loop / lappy 对数据进行子集和绘图
【发布时间】:2018-01-30 17:42:01
【问题描述】:

我有大约 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)

创建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)

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

【问题讨论】:

  • 您的一个问题来自plot &lt;- windows() 命令(它跨越代码中的多行,但这就是它执行的内容)。因此,您的代码会打开一个新窗口,将结果 (NULL) 存储为 plot,创建一个 ggplot 对象但不保存它,然后打印 plot(同样是 NULL)。如果你把它改成plot &lt;- ggplot(...,就可以了。

标签: r plot ggplot2


【解决方案1】:

我建议使用 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,您只需将数据参数替换为.。请注意,当您想要一次循环浏览多个事物时(例如,如果您希望标题不同。

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

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

【讨论】:

  • 酷,这是一个有趣的方法!我一定会记得的!我非常感谢如何存储我的地块。再次感谢
【解决方案2】:

试试这个:

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<-
        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)
    windows()
    print(plot)
  }
}

type.graph(df2)

【讨论】:

  • 是的,我相信。
【解决方案3】:

几年前,在 tidyverse 之前,我曾使用 ggplot2 以与您类似的方式生成绘图对象列表。 在自定义函数的末尾,我使用明确的return() 语句来返回创建的对象。这对我有用(例如,稍后运行ggsave())。

以df 作为主要数据集的自定义直方图示例,后跟一些额外参数:

ggHistFunc <- function (cl, df, ymax, st) {
    mn <- st$means[st$variable==cl]
    P50 <- st$medians[st$variable==cl]
    P10 <- st$P10[st$variable==cl]
    P90 <- st$P90[st$variable==cl]
    gghist <-
        ggplot(data = df, aes_string(x = cl)) +
        geom_histogram(binwidth = diff(range(df[,cl]))/10, aes(y = ..count..),
                       fill = "white", colour = "black") +
        geom_line(data = data.frame(x = c(mn, mn)), y = c(0, ymax),
                  aes(x=x), colour="green", size=1) +
        geom_line(data = data.frame(x = c(P50, P50)), y = c(0, ymax),
                  aes(x=x), colour="brown", size=1) +
        geom_line(data = data.frame(x = c(P10, P10)), y = c(0, ymax),
                  aes(x=x), colour="blue", size=1) +
        geom_line(data = data.frame(x = c(P90, P90)), y = c(0, ymax),
                  aes(x=x), colour="red", size=1)
    #print(gghist)
    return(gghist)
}

然后是“循环”为所有参数创建直方图:

gg_Hist_HM <- lapply(X = as.list(names(params_HM)),
                     FUN = ggHistFunc, df = params_HM, ymax = 100, st = stat_HM)

现在我看到上面提出的带有 purrr 包的方法看起来更优雅!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多