jimbo
jimbo

Reputation: 176

Add titles to ggplots created with map()

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

Upvotes: 6

Views: 1883

Answers (3)

Paul
Paul

Reputation: 9087

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

Upvotes: 11

yang
yang

Reputation: 739

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.

Upvotes: 0

CPak
CPak

Reputation: 13581

Perhaps you'd be interested in using facet_wrap instead

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

Upvotes: 1

Related Questions