rggplot2gridextra

Try to put multiple ggplot into one image but all plot are same


I am trying to put multiple ggplot chart into one but all the plot are same, please help with below example:

library(tidyverse)
library(gridExtra)

url <- paste("https://raw.githubusercontent.com/fivethirtyeight/",
  "data/master/college-majors/recent-grads.csv",
  sep = ""
)
df <- read_csv(url)
cols_to_factor <- c("Major", "Major_code", "Major_category")
df <- df %>%
  mutate_at(cols_to_factor, factor)
df_clean <- df %>% drop_na()

plot_list <- list()
i <- 0
for (variable in colnames(select_if(df_clean, is.numeric))) {
  i <- i + 1
  g <- ggplot(df_clean) +
    geom_histogram(aes(unlist(df_clean[, variable])),
      bins = 20,
      fill = "royalblue", color = "gray"
    ) +
    ggtitle(paste("Histogram of", variable)) +
    labs(x = variable)
  plot_list[[i]] <- g
}
grid.arrange(grobs = plot_list, ncol = 5)

The plot_list does have values inside, but I don't know why they are all same. Each loop the value should be different. If I add plot(g) befor plot_list[[i]]<-g, it can draw the correct chart. I am out of ideas, please kindly help. Thank you!


Solution

  • You can achieve the desired result with facet_wrap()

    library(tidyverse)
    
    df_clean %>% 
      select(where(is.numeric)) %>% 
      pivot_longer(everything()) %>% 
      ggplot(aes(x = value)) + 
      geom_histogram(bins = 20, fill = "royalblue", color = "gray") + 
      facet_wrap(~ name, scales = "free")
    

    enter image description here