【问题标题】:Sending dataframes within list to a plot function将列表中的数据框发送到绘图函数
【发布时间】:2017-12-16 11:01:09
【问题描述】:

我正在尝试从多个数据框制作多个 ggplot 图表。我已经开发了下面的代码,但最后的循环不起作用。

df1 <- tibble(
  a = rnorm(10),
  b = rnorm(10)
)

df2 <- tibble(
  a = rnorm(20),
  b = rnorm(20)
)

chart_it <- function(x) {
  x %>% ggplot() +
    geom_line(mapping = aes(y=a,x=b)) +
    ggsave(paste0(substitute(x),".png"))
}

ll <- list(df1,df2)

for (i in seq_along(ll)) {
 chart_it(ll[[i]])
}

我知道这与它有关

ll[[i]]

但我不明白为什么,因为当我把它放在控制台中时,它会给出我想要的数据框。另外,有没有办法用地图函数而不是 for 循环来做到这一点?

【问题讨论】:

    标签: r list for-loop ggplot2


    【解决方案1】:

    我假设您想在最后看到两个名为 df1.pngdf2.png 的文件。

    您需要以某种方式将数据帧的名称传递给函数。一种方法是通过命名列表,将名称与列表元素的内容一起传递。

    library(ggplot2)
    library(purrr)
    
    df1 <- tibble(
      a = rnorm(10),
      b = rnorm(10)
    )
    
    df2 <- tibble(
      a = rnorm(20),
      b = rnorm(20)
    )
    
    chart_it <- function(x, nm) {
      p <- x %>% ggplot() +
        geom_line(mapping = aes(y=a,x=b))
      ggsave(paste0(nm,".png"), p, device = "png")
    }
    
    ll <- list(df1=df1,df2=df2)
    
    for (i in seq_along(ll)) {
      chart_it(ll[[i]], names(ll[i]))
    }
    

    在 tidyverse 中,您可以使用以下命令替换循环而不修改函数。

    purrr::walk2(ll, names(ll),chart_it)
    

    或者干脆

    purrr::iwalk(ll, chart_it)
    

    还有imaplmap,但它们会在控制台中留下一些输出,我猜这不是你想做的。

    【讨论】:

    • 太完美了。非常感谢:)
    【解决方案2】:

    问题出在您的chart_it 函数中。它不返回ggplot。尝试将管道的结果保存到变量中并return() (或将其作为函数中的最后一条语句)。

    类似

    chart_it <- function(x) {
      chart <- x %>% ggplot() +
        geom_line(mapping = aes(y=a,x=b))
    
        ggsave(paste0(substitute(x),".png")) # this will save the last ggplot figure
    
        return(chart)
    }
    

    【讨论】:

    • 感谢您的回复。如果我运行chart_it(df1),它会保存绘图,那么这是否意味着我的功能没问题?
    • 尝试了以下chart_it &lt;- function(x) { x %&gt;% ggplot() + geom_line(mapping = aes(y=a,x=b)) + ggsave(paste0(substitute(x),".png")) -&gt; chart return(chart) },我得到“错误:device 必须为 NULL、字符串或函数。”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    相关资源
    最近更新 更多