2

For exploratory analysis, its often useful to quickly plot multiple variables in one grid. An easy way to do this is to:

data(mtcars)    
hist(mtcars[,c(1,2,3,4)])

enter image description here

However, it becomes difficult to adjust breaks and axes to maintain consistency i.e.

hist(mtcars[,c(1,2,3,4)], breaks = 10)

does not effect the histograms. Is there an easy work around this or an easy way to do this in ggplot2?

Gooze
  • 110
  • 1
  • 1
  • 11
  • 1
    `hist(mtcars[c(1,2,3,4)])` doesn't work. what do you see on your screen? – amatsuo_net Jul 28 '17 at 14:27
  • After loading `mtcars`, your code `hist(mtcars[c(1,2,3,4),1])` produces an error: `Error in hist.default(mtcars[c(1, 2, 3, 4)]): 'x' must be numeric` – abichat Jul 28 '17 at 14:28
  • Sorry for the late reply, i had computer issues and then forgot about this. The code runs fine for me in RStudio, however perhaps its best to put a comma before the column specification: hist(mtcars[,c(1,2,3,4)]) – Gooze Sep 25 '17 at 08:49

2 Answers2

7

This is how to do it with hist() :

lapply(mtcars[1:4], FUN=hist)

However I prefer to store plots in R objects with ggplot2 and display plot lists with cowplot::plotgrid() :

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

cowplot::plot_grid(plotlist = list)
Paul Endymion
  • 537
  • 3
  • 18
  • Thanks, i think i can work with this by changing 1:ncol(mtcars) to 1:4. When i run lapply(mtcars[1:4], FUN=hist), however, i do not get the desired result above. Do you know why that is? – Gooze Sep 25 '17 at 09:20
4

With ggplot2 you can use facet_wrap to create a grid based on other variables.

For example:

library(ggplot2)

data(mtcars)

ggplot(data = mtcars) +
    geom_histogram(aes(x = mpg), bins = 4, colour = "black", fill = "white") +
    facet_wrap(~ gear)

example histogram with facets

And you can use the bins parameter to easily set how many breaks you want.

Paolo
  • 3,825
  • 4
  • 25
  • 41
  • This isn't quite what OP wants--OP is asking for how to plot histograms of each column, not of one column by another. – Gregor Thomas Jul 28 '17 at 14:48
  • @Gregor I realize that now after seeing the other answer (which works and seems to answer the question) – Paolo Jul 28 '17 at 14:50