Search code examples
rdplyrdensity-plot

Save density plot for each column in pdfs


I want to create a density plot for each numerical column of a dataset and then the save the output as the column names.

To preserve data anonymity, I'll use mtcars.

My ideal output would be density plots saved as the following:

mpg.pdf
cyl.pdf
disp.pdf
hp.pdf
drat.pdf
qsec.pdf
vs.pdf
am.pdf
gear.pdf
carb.pdf

My attempt, which obviously doesn't work..

library(dplyr)
library(ggplot2)
col_tmp <- colnames(mtcars)

make_plots <- function(col){
  column <- mtcars %>% select(col) 
  col_plot <- column %>%
    ggplot( aes(x=col)) +
    geom_density(fill="#69b3a2", color="#e9ecef", alpha=0.8)
  
  ggsave(col_plot, file="col.pdf")
}

lapply(mtcars, make_plots(col_tmp))

I thought maybe the issue was parsing the column names from the vector into the function? I tried using [[col]] but that didn't work either...


Solution

  • There's a few ways. One is to use the .data construction.

    make_plots <- function(col){
      col_plot <- mtcars %>%
        ggplot(aes(x = .data[[col]])) +
        geom_density(fill = "#69b3a2", color = "#e9ecef", alpha = 0.8)
      
      file_name <- paste0(col, ".pdf")
      ggsave(col_plot, file = file_name)
    }
    
    lapply(col_tmp, make_plots)
    

    Note that your lapply did not work, and that selecting the column isn't necessary.