Q:

How to set y axis limits when using map2(~ggplot...?

How can I set different y axis limits in each plot when using purrr::map2?
I would like to set the y-axis lower limit to half the maximum y-axis value, something like: max(y-axis value/2).
data(mtcars)

library(tidyverse)

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

plots <- map2(
  mtcars_split,
  names(mtcars_split),
  ~ggplot(data = .x, mapping = aes(y = mpg, x = wt)) + 
    geom_jitter() +
    ggtitle(.y)+
  scale_y_continuous(limits=c(max(.y)/2,NA))

)

plots

Error in max(.y)/2 : non-numeric argument to binary operator

A:

.y is the name of the dataframe, which is why max(.y)/2 is giving you that error. This should give you what you want:
plots <- imap(
  mtcars_split,
  ~ggplot(data = .x, mapping = aes(y = mpg, x = wt)) + 
    geom_jitter() +
    ggtitle(.y) +
    scale_y_continuous(limits=c(max(.x$mpg)/2,NA))
)

Note that imap(x, ...) is just shorthand for map2(x, names(x), ...).

A:

This doesn't work based on the y-axis value, but it gets the job done if you don't mind specifying your y-column twice:
plots <- map2(
  mtcars_split,
  names(mtcars_split),
  ~ggplot(data = .x, mapping = aes(y = mpg, x = wt)) + 
    geom_jitter() +
    ggtitle(.y)+
  scale_y_continuous(limits=c(max(.x$mpg)/2,NA))

)

Or maybe a safer option:
plots <- map2(
    mtcars_split,
    names(mtcars_split),
    ~{
        ploty <- 'mpg'
        plotx <- 'wt'
        ggplot(data = .x, mapping = aes_string(y = ploty, x = plotx)) + 
        geom_jitter() +
        ggtitle(.y)+
        scale_y_continuous(limits=c(max(.x[[ploty]])/2,NA))
    }
)

