6

What's the easiest way to add titles to each ggplot that I've created below using the map function? I want the titles to reflect the name of each data frame - i.e. 4, 6, 8 (cylinders).

Thanks :)

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

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

plots
jimbo
  • 176
  • 6

3 Answers3

11

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)
)
Paul
  • 8,734
  • 1
  • 26
  • 36
1

Perhaps you'd be interested in using facet_wrap instead

ggplot(mtcars, aes(y=mpg, x=wt)) + geom_jitter() + facet_wrap(~cyl)
CPak
  • 13,260
  • 3
  • 30
  • 48
0

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.

yang
  • 719
  • 3
  • 11