我正在以编程方式制作一系列绘图,并且我想将 tibble(或数据帧)的名称传递到我的 ggplot2 图的标题中,这样我就知道哪个是哪个。
deparse(substitute(x))
适用于从 tibble 制作单个图,但通过 purrr::map( 调用时输出
当从 tibbles 列表中绘制绘图时。 "."
)
#initialize data frame
myDf <- tibble(x = LETTERS[1:5], y = sample(1:10, 5))
#initialize function
myPlot <- function(df) {
title = deparse(substitute(df))
ggplot(df, aes(x, y)) +
geom_col() +
ggtitle(title)
}
#call function
myPlot(myDf)
这给了我一个标题为myDF
的图。
现在我想对绘图列表做同样的事情:
#initialize list of data frames
myDFs <- vector("list", 0)
myDFs$first <- tibble(x = LETTERS[1:5], y = sample(1:10, 5))
myDFs$second <- tibble(x = LETTERS[1:5], y = sample(1:10, 5))
myDFs$third <- tibble(x = LETTERS[1:5], y = sample(1:10, 5))
#initialize same function
myPlot <- function(df) {
title = deparse(substitute(df))
ggplot(df, aes(x, y)) +
geom_col() +
ggtitle(title)
}
#call function with purrr::map
map(myDFs, myPlot)
现在每个标题都具有相同的标题:.x[[i]]
我很想知道如何通过 map 传递信息更丰富的标题。它不必很漂亮,但它必须是独一无二的。预先感谢您!
最佳答案
我们可以使用专为此类操作而设计的imap
myPlot <- function(df, names) {
ggplot(df, aes(x, y)) +
geom_col() +
ggtitle(names)
}
purrr::imap(myDFs, myPlot)
关于r - 通过 `map()` 传递名称以进行延迟评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57300708/