r - 将标题添加到将与 map() 一起使用的函数中的 ggplot 对象

标签 r function ggplot2 purrr

我有一个函数可以做几件事,包括生成 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 遍历 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]]

关于r - 将标题添加到将与 map() 一起使用的函数中的 ggplot 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70386547/

相关文章:

r - 存在并应用 : why are these functions different?

Python列表检查两个最大值是否相同

r - R 中一周中的每一天的 geom_密度()

r - ggplot 颜色图例形状混合字母数字和形状

r - 使用 case_when 突变 - 多个 LHS/RHS OR 评估

java - RCaller 3.1 入门

Rcpp 子集 DataFrame 的行

c - c函数声明中的 "..."是什么意思?

java - 如何将字符串切成两部分并将子字符串传递给不同的函数?

r - ggplot2 中的多个 y 超过 x