1

I see this code :

list <-lapply(1:ncol(mtcars), function(col) ggplot2::qplot(mtcars[[col]], geom = "histogram",binwidth = 1)) cowplot::plot_grid(plotlist = list)

surggest by Paul Endymion to respond to "Plotting multiple histograms quickly in R".

I try that code, and it work well. But, I don't know how to add x labels in that code because all histograms are labeled histdata[[col]]. Can you help me?

Thanks.

2 Answers2

0

with xlab = names(mtcars)[col]) you can access the names of the dimensions

list <-lapply(1:ncol(mtcars), function(col) ggplot2::qplot(mtcars[[col]], geom = "histogram",binwidth = 1, xlab = names(mtcars)[col])) 
    cowplot::plot_grid(plotlist = list)
Domingo
  • 613
  • 1
  • 5
  • 15
0

Don't use list as a variable name since list() is the constructor for list objects. It will only lead to confusion.

You can simply use the xlab argument of qplot:

l <-lapply(1:ncol(mtcars), function(col) ggplot2::qplot(mtcars[[col]], geom = "histogram",binwidth = 1, xlab = names(mtcars)[col])) 
cowplot::plot_grid(plotlist = l)

However, since you are using ggplot, it would be more elegant to go with a tidyverse solution to begin with:

library(tidyverse)

mtcars %>% 
  select_if(is.numeric) %>% 
  gather("var", "val") %>% 
  ggplot() + 
  geom_histogram(aes(val), bins = 10) +
  facet_wrap(~var, scales = "free")

shs
  • 3,683
  • 1
  • 6
  • 34