Reputation: 110
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)])
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
?
Upvotes: 2
Views: 28548
Reputation: 561
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)
Upvotes: 7
Reputation: 3955
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)
And you can use the bins
parameter to easily set how many breaks you want.
Upvotes: 4