Add titles to ggplots created with map()

﹥>﹥吖頭↗ 提交于 2019-11-30 15:01:02

Use map2 with names.

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

Edit: alistaire pointed out this is the same as imap

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

Perhaps you'd be interested in using facet_wrap instead

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

You can use purrr::map2():

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

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

EDIT

Sorry duplicated with Paul's answer.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!