在R中的函数内绘制多个图

时间:2018-06-25 13:10:29

标签: r function loops lapply gridextra

我有一个列表colName,其中包含数据框isNumValLong的列名。此列表的每个元素都是一个包含6个列名的字符向量。

column names in a list

isNumValLong是包含传递给函数plothist()的列名的值的数据框:

Struct of the dataframe

我打算将colName传递给plothist,这将在每个调用中的6个变量集中创建多个图。

plothist <- function(colName, myDf) {
  #str(name)
  #class(name)
  l <- length(colName)
  ls <- list()
  for (i in 1:l) {
    ls[[i]] <- isNumValLong %>% filter(key %in% colName[i]) %>%
      ggplot(aes(x = value)) + geom_histogram() + facet_grid(. ~ key, scales = "free")

  }
  grid.arrange(ls)
}

我的函数调用如下:

lapply(colName, plothist, isNumValLong)

函数返回错误

enter image description here

请让我知道我哪里错了?

@MrFlik,这是可复制的代码:

library(ggplot2)
library(tidyr)
library(gridExtra)

plothist <- function(name, myDf) {
  #str(name)
  #class(name)
  l <- length(name)
  ls <- list()
  for (i in 1:l) {
    ls[[i]] <- myDf %>% filter(key %in% name[i]) %>%
      ggplot(aes(x = value)) + geom_histogram() + ggtitle(label = as.character(name[i]))

  }
  grid.arrange(ls)
}


u <- rnorm(10^6)
v <- rnorm(10^6)
w <- rnorm(10^6)
x <- rnorm(10^6)
y <- rnorm(10^6)
z <- rnorm(10^6)

isNumVal <- data.frame(cbind(u, v, w, x, y, z))
isNumValLong <- gather(isNumVal, key = "key", value = "value")
colName <- as.character(unique(isNumValLong$key))
colName <- split(colName, ceiling(seq_along(colName)/2))

lapply(colName, plothist, isNumValLong)

预期输出应为3组图,每个图具有两个子图。示例第一个集合如下所示:

example 1st set:

1 个答案:

答案 0 :(得分:1)

也许这就是您想要的? 我对您的函数做了一点修改,所以您只需要传递data.frame而不是唯一名称,就可以传递用于绘图的行数和列数。

library(ggplot2)
library(tidyr)
library(dplyr)
library(gridExtra)

u <- rnorm(10^3); v <- rnorm(10^3)
w <- rnorm(10^3); x <- rnorm(10^3)
y <- rnorm(10^3); z <- rnorm(10^3)

isNumVal <- data.frame(cbind(u, v, w, x, y, z))
isNumValLong <- gather(isNumVal, key = "key", value = "value")

plothist <- function(myDf, ncols=3, nrows=2) {
  uniqueKey <- unique(myDf$key)
  ls <- list()
  for (i in 1:length(uniqueKey)) {
    myDfPlot =  myDf %>% filter(myDf$key %in% uniqueKey[i])
    ls[[i]] = ggplot(myDfPlot, aes(value)) +  
      geom_histogram() + 
      ggtitle(label = as.character(paste("Key:", as.character(uniqueKey[i]),
                                         "\t Mean:", as.character(round(mean(myDfPlot$value, na.rm = TRUE),4)),
                                         "\t Median:", as.character(round(median(myDfPlot$value, na.rm = TRUE),4))   
      ), sep = ", "))

  }
  marrangeGrob(ls, ncol = ncols, nrow = nrows)
}

plothist(isNumValLong)
plothist(isNumValLong,2,1)