【问题标题】:How to add titles to multiple plots of data frames within a list?如何为列表中的多个数据框图添加标题?
【发布时间】:2019-05-08 14:44:51
【问题描述】:

我正在尝试使用 ggplot 为包含在名为“list1”的列表中的 20 个数据帧(“df1”-“df20”)创建图。该列表如下所示:

list1 <- list(df1, df2, ..., df20)

每个数据框都有两列 z 和 y,我想将它们相互绘制:

df1
z  y
1  6
2  9
3  7

我创建了以下代码,它也可以工作,但它没有提供从 df1 到 df20 的相应标题的图:

lapply(list1, function(x) 
  ggplot(data = list1$x) + 
    geom_line(mapping = aes(x = x$z, 
                          y = x$y)))

我尝试将所有名称放在一个向量中,并在代码中包含这个向量,如下所示:

titlenames <- c(df1, df2, ..., df20)

+ ggtitle(titlenames) 

但这只是提供了所有情节的名字。

感谢任何帮助,因为我对 R 还是很陌生。

【问题讨论】:

标签: r ggplot2


【解决方案1】:

您可以尝试使用mapply(类似于lapply,但首先使用函数,并且可以遍历多个等长列表/向量)与数据列表和名称向量:

mapply(function(df, titlename) {
    ggplot(data = df) + 
        geom_line(mapping = aes(x = z, y = y)) +
        ggtitle(titlename)
}, list1, titlenames)

我发现因为mapply的格式与lapply不同,所以很难记住。 purrr 包提供了我认为更清洁的替代方案:

purrr::map2(list1, titlenames, function(df, titlename) {
    ggplot(data = df) + 
        geom_line(mapping = aes(x = z, y = y)) +
        ggtitle(titlename)
})

【讨论】:

  • 太棒了,谢谢! mapply 函数起初无法正常工作,但使用 purrr 包一切正常。
猜你喜欢
  • 2022-07-05
  • 1970-01-01
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
  • 2021-12-18
  • 2020-09-15
  • 2023-02-23
  • 2015-07-05
相关资源
最近更新 更多