我有一个函数可以做几件事,包括生成 ggplot 对象。然后我将此函数传递给 purrr::map() 以迭代嵌套数据。我需要将 id
作为 ggtitle
添加到我函数中的每个 ggplot
对象,但是 ggplot
对象是由另一个 R 包中的另一个函数创建,因此我必须在我的函数中创建 ggplot
对象之后添加 ggtitle
。当我尝试使用 purrr::map()
进行迭代时,出现错误。
我认为这个线程可能会有帮助,但我不知道如何为我的示例编写代码:Add titles to ggplots created with map()
这是一个非常简化的函数,我认为它重现了我的问题:
library("tidyverse")
dat <-
structure(list(id = c("07060710", "07060710", "07060710", "07060710",
"07060710", "07060710", "07060710", "07060710", "07060710", "07060710",
"07263295", "07263295", "07263295", "07263295", "07263295", "07263295",
"07263295", "07263295", "07263295", "07263295"), y = c(-0.1,
0.1, 0, 0, -0.1, -0.1, -0.1, 0, -0.1, -0.2, 0.4, 0.5, 0.5, 0.5,
0.9, 0.7, 0.9, 0.9, 0.4, 0.4), x = c(1, 1.8, 1.3, 1.3, 0.7, 0.3,
1.5, 0.9, 1, 0.5, 1.1, 1, -0.1, -0.4, 3.2, 2.4, 3, 3.3, 0.7,
1)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-20L))
runLM = function(df) {
# Here I try to extract the id
# And I think this is what causes the error
id_title <- unique(df$id)
lm_fit <- lm(y ~ x, data = df)
# This is a simplified plot function for this example
# The actual initial plot is created by a function from another package
# So I cannot manipulate the initial ggplot function
# I can only manipulate the ggplot object after it is created
plot_init <-
df %>%
ggplot(aes(x = x, y = y)) +
geom_point()
# Here I try to add the 'id' as a the plot title
plot_fin <- plot_init +
ggtitle(id_title)
return(plot_fin)
}
然后我将这个函数传递给:
fit_lm <-
dat %>%
group_by(id) %>%
nest() %>%
mutate(model = map(data, ~runLM(df = .x)))
# Here should be the plot, but I get an error when I try to iterate using map()
fit_lm[[3]][[1]]
最佳答案
嵌套后,列表列data
中存储的数据帧中没有列id
。而是向您的函数添加参数 id_title
并使用 map2
遍历 id
和 data
列您的嵌套数据:
library("tidyverse")
runLM = function(df, id_title) {
lm_fit <- lm(y ~ x, data = df)
plot_init <-
df %>%
ggplot(aes(x = x, y = y)) +
geom_point()
plot_fin <- plot_init +
ggtitle(id_title)
return(plot_fin)
}
fit_lm <- dat %>%
group_by(id) %>%
nest() %>%
mutate(model = map2(data, id, ~runLM(df = .x, id_title = .y)))
fit_lm$model
#> [[1]]
#>
#> [[2]]
关于r - 将标题添加到将与 map() 一起使用的函数中的 ggplot 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70386547/