how do I integrate pmap with a ggplot function?

62 Views Asked by At

I'm trying to use a ggplot function that I can use in a pipe with pmap, feeding a tibble of variables. These variables include the data frame, filtering options and plotting variables.

The function works but in the context of pmap it doesn't with an error: Error in UseMethod("filter") : no applicable method for 'filter' applied to an object of class "character"

library(tidyverse)
library(palmerpenguins)

make_plot <- function(dat, species) {
  dat %>%
    filter(.data$species == .env$species) %>%
    ggplot() +
    aes(bill_length_mm, body_mass_g, color=sex) +
    geom_point() +
    ggtitle(glue("Species: {species}")) +
    xlab("bill length (mm)") +
    ylab("body mass (g)") +
    theme(plot.title.position = "plot")
}

species <- c("Adelie", "Chinstrap", "Gentoo")
penguins_vars <- tibble(dat = rep("penguins", 3), species = species)

plots <- pmap(penguins_vars, make_plot)

#function still works:
make_plot(penguins, "Adelie")
1

There are 1 best solutions below

2
Marcus On

pmap essentially iterates through the rows of the tibble (penguins_vars) so when it's called, make_plot is passed the string "penguins" not the data set (like it is in the working call). I think you want something like this:

plots <- map(species, make_plot, dat = penguins)