【问题标题】:Add titles to ggplots created with map()为使用 map() 创建的 ggplots 添加标题
【发布时间】:2018-07-06 10:08:25
【问题描述】:

使用 map 函数向我在下面创建的每个 ggplot 添加标题的最简单方法是什么?我希望标题反映每个数据框的名称 - 即 4、6、8(圆柱体)。

谢谢:)

mtcars_split <- 
  mtcars %>%
  split(mtcars$cyl)

plots <-
  mtcars_split %>%
  map(~ ggplot(data=.,mapping = aes(y=mpg,x=wt)) + 
        geom_jitter() 
  # + ggtitle(....))

plots

【问题讨论】:

    标签: r ggplot2 purrr


    【解决方案1】:

    map2names 一起使用。

    plots <- map2(
      mtcars_split,
      names(mtcars_split),
      ~ggplot(data = .x, mapping = aes(y = mpg, x = wt)) + 
        geom_jitter() +
        ggtitle(.y)
    )
    

    编辑:alistaire 指出这与imap 相同

    plots <- imap(
      mtcars_split,
      ~ggplot(data = .x, mapping = aes(y = mpg, x = wt)) + 
        geom_jitter() +
        ggtitle(.y)
    )
    

    【讨论】:

    • @alistaire,是的 - 忘了 imap。我已更新我的答案以包含 imap。
    【解决方案2】:

    也许您有兴趣改用facet_wrap

    ggplot(mtcars, aes(y=mpg, x=wt)) + geom_jitter() + facet_wrap(~cyl)
    

    【讨论】:

      【解决方案3】:

      你可以使用purrr::map2():

      mtcars_split <- mtcars %>% split(mtcars$cyl)
      
      plots <- map2(mtcars_split, titles, 
        ~ ggplot(data=.x, aes(mpg,wt)) + geom_jitter() + ggtitle(.y)
      )
      

      编辑

      抱歉,与 Paul 的 回答重复。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-18
        • 1970-01-01
        • 2020-05-13
        • 1970-01-01
        • 2020-03-24
        • 2020-05-11
        • 1970-01-01
        • 2021-12-18
        相关资源
        最近更新 更多