Search code examples
rggplot2tidyverselapply

struggling with lapply and column names in a plot matrix


I'm struggling to create a matrix of histograms using lapply(). The following produces nine histograms but the x labels are the values in the first row of the data, rather than the column names. I'm hoping for the x labels to be the names of the columns.

library(tidyverse)
library(ISLR2)
library(gridExtra)
data(College)
plothists<-function(colm) {
  ggplot(College) + geom_histogram(aes(colm),binwidth=20)+xlab(label=colm)
}
plist<-lapply(College[,c(2:10)],plothists)
grid.arrange(grobs=as.list(plist),ncol=3)

How can I get column names as x labels?

Edit: I'm accepting JPSmith's answer but I have modified the code for my own purposes as follows:

library(tidyverse)
library(ISLR2)
data(College)
College |>
  pivot_longer(2:10,names_to="var") |>
  ggplot(aes(value)) + geom_histogram(bins=60) +
  facet_wrap(~var,scales="free") +
  theme(axis.text.x=element_text(angle=45,hjust=1))

Solution

  • You can achieve this with your current libraries by simply transforming your data to long format and using ggplot:

    # transform to long
    newdata <- College %>% 
      pivot_longer(2:10, names_to = "hist") 
    
    ggplot(newdata) + 
      geom_histogram(aes(value), binwidth = 20) + 
      facet_wrap(~hist, ncol = 3, scales = "free")
    

    Output: enter image description here