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?
CodePudding user response:
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")
CodePudding user response:
I found an easier way to do this as
library(tidyverse)
library(ISLR2)
data(College)
library(reshape2)
cmelt<-melt(College[,c(2:10)])
ggplot(cmelt,aes(value)) geom_histogram(bins=60)
facet_wrap(~variable,scales="free")
theme(axis.text.x=element_text(angle=45,hjust=1))
in a different stack overflow question!