在将与 map() 一起使用的函数中将标题添加到 ggplot objects

Add title to ggplot objects in function that will be used with map()

我有一个函数可以做几件事,包括生成 ggplot objects。然后我将此函数传递给 purrr::map() 以迭代嵌套数据。我需要在我的函数中为每个 ggplot object 添加一个 id 作为 ggtitle,但是 ggplot object 是由另一个创建的来自另一个 R 包的函数,所以我必须在我的函数中创建 ggplot object 之后添加 ggtitle。当我尝试使用 purrr::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 遍历嵌套数据的 iddata 列:

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]]

另一种选择是不嵌套,而是使用group_split。然后你可以在没有第二个参数的情况下使用你的原始函数。

也不需要使用 mutate。

dat %>% 
  group_split(id) %>% 
  map(runLM)
#> [[1]]

#> 
#> [[2]]