how to draw geom_histogram() for each column and save it

library(ggplot2)
library(dplyr)
library(palmerpenguins)

penguins <- penguins %>%  tidyr::drop_na()


my_plot <- function(x_var) {
  p <- penguins %>%
    ggplot(aes(x = {{ x_var }})) +
    geom_histogram()

  x_var_name <- dplyr::quo_name(enquo(x_var))

  ggsave(
    filename = stringr::str_glue("{x_var_name}.png"),
    plot = p
  )
}



penguins %>%
  select(ends_with("_mm")) %>%
  purrr::map(my_plot)
#> Error in `expr_name()`:
#> ! `expr` must be a symbol, scalar, or call.

#> Backtrace:
#>     ▆
#>  1. ├─penguins %>% select(ends_with("_mm")) %>% ...
#>  2. └─purrr::map(., my_plot)
#>  3.   └─global .f(.x[[i]], ...)
#>  4.     └─dplyr::quo_name(enquo(x_var))
#>  5.       └─rlang::expr_name(quo_squash(quo))
#>  6.         └─rlang::abort(...)

Created on 2022-09-22 with reprex v2.0.2

I don't know how to write it. Can you give me some help? thanks

I find it easier to work with the column names as strings.

library(ggplot2)
library(dplyr)
library(palmerpenguins)
penguins <- penguins %>%  tidyr::drop_na()


my_plot <- function(x_var) {
  p <- penguins %>%
    ggplot(aes_string(x = x_var)) +
    geom_histogram()

  ggsave(
    filename = stringr::str_glue(x_var,".png"),
    plot = p
  )
}

penguins %>%
  select(ends_with("_mm")) %>%
  colnames() |> 
  purrr::walk(my_plot)
2 Likes

Just to add a little color commentary to @FJCC's excellent answer, note the use of purrr::walk().

This passage from AO Smith's post (see link below), Automating exploratory plots with ggplot2 and purrr, explains the difference nicely:

The walk() function is part of the map family, to be used when you want a function for its side effect instead of for a return value. Saving plots is a classic example of when we want walk() instead of map() .

1 Like