【问题标题】:Printing plots through a function通过函数打印绘图
【发布时间】:2018-06-04 12:54:13
【问题描述】:

我有一个列表,

item1 <- list(1:5)
item2 <- list(5:10)
item3 <- list(ggplot(mtcars, aes(x=as.factor(cyl) )) + geom_bar())

list <- list("item1"=item1, "item2"=item2, "item3.plt"=item3)

在这种情况下,其中一个列表项将“.plt”作为其名称的一部分。 (其中包含一个 ggplot 图)

我正在编写一个函数来将此列表作为参数,以便它将所有具有“.plt”部分的项目打印为图形对象。

print.plots <- function(x){

e <- list2env(x) #do I need this?

list <- list()
  a <- deparse(substitute(x))
  for(i in 1:length(names(x))){
    if(grepl(".plt", names(x)[i])){
      list[i] <- list(paste0(paste0(a,"$"),names(x)[i]))
      # Print here?
    }

  }
  return(list)
}

print.plots(list)

我已经输入了return(list) 来查看输出是什么,它显示了一个包含 3 个项目的列表,前两个是 NULL,第三个是我需要打印的情节的名称。

[[1]]
NULL
[[2]]
NULL
[[3]]
"list$item3.plt"

我的if 条件似乎不包括名称中没有“.plt”的列表项,并且情节本身没有被打印(即使我删除了return 语句)。有人可以帮忙吗?

【问题讨论】:

  • 为什么要创建函数?只需在控制台list 中调用您的列表,您就应该能够看到这些图。或者干脆使用print(list) 这应该在您的列表中绘制图。只是好奇。为什么您的列表是嵌套列表?为什么不只是一个简单的列表?

标签: r list ggplot2


【解决方案1】:

简单的事情

list[grepl("\\.plt", names(list))]

应该给你一个非常接近我认为你想要形成你的 print.plots 函数的结果。

关于写一个函数,有几点建议。

  1. 避免使用单词list 作为对象。在下面的示例中,我将使用mylist

  2. print_plots 使用下划线,而不是点。 print.plots 可能会导致 S3 类出现一些问题。

在以下示例中,我们查找以 .plt 作为项目结尾的任何项目,然后返回名称并打印绘图。

library(ggplot2)

item1 <- list(1:5)
item2 <- list(5:10)
item3 <- list(ggplot(mtcars, aes(x=as.factor(cyl) )) + geom_bar())

mylist <- list("item1"=item1, "item2"=item2, "item3.plt"=item3)

print_plots <- function(x) { 
  plts <- grepl("\\.plt", names(x))

  if (any(plts)) {
    message(sprintf("Plots in %s are:", deparse(substitute(x)))) 
    lapply(which(plts), function(i) {y <- unlist(x[i], recursive = FALSE); print(y)}) 
  } else {
    message(sprintf("There are no plots in %s.", deparse(substitute(x)))) 
  }
  invisible(NULL)
}

print_plots(mylist)
# Plots in mylist are:
# $item3.plt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多