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?

3
  • 1
    hist(mtcars[c(1,2,3,4)]) doesn't work. what do you see on your screen? Jul 28, 2017 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, 2017 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, 2017 at 8:49

2 Answers 2

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)
1
  • 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, 2017 at 9: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.

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.