1

I'm trying to produce plots by iterating among levels of a split dataframe, and subsequently giving each plot a title showing which level it came from.

I've tried adding a title as follows: ggtitle() using names() as the argument for ggtitle(), but this doesn't actually title anything.

mtcars %>% 
  split(.$cyl) %>% 
  map(~ggplot(., aes(mpg, wt)) + geom_point() + ggtitle(names(.$cyl)))

Created on 2019-05-28 by the reprex package (v0.2.1)

The above code produces a list with elements 4, 6, and 8, and for each element, a scatterplot of mpg vs wt. However, I would like each of the plots to have as its title the level split it came from, because with larger datasets containing more levels, it would be painful to track which plot corresponds to which level split.

I appreciate any assistance with this.

Chris A.
  • 369
  • 2
  • 14
  • 3
    Use `imap`, which was added to `purrr` a few versions in. It gives access to the list names as you iterate. That's just a wrapper around `map2(x, names(x))`. Where you've called `names(.$cyl)`, you're looking for the names of the `cyl` column, which won't really make sense – camille May 28 '19 at 20:05

0 Answers0