Reputation: 1049
I'm drawing eight histograms by means of a for-loop in R and I want to plot them all as one picture (as 2 columns by 4 rows). I was trying to do the same thing as this person did (Multiple histograms in ggplot2), but somehow for me it doesn't work.
This is (part of) my code:
Words = levels(study$Word)
numberOfWords = length(levels(study$Word))
layout(matrix(1:8,4,2,byrow=TRUE))
par(mar=c(2,1,2,1))
for (i in 1:numberOfWords) {
word <- Words[i]
histo <- ggplot(study[study$Word==word,], aes(study$VOT[study$Word==word]))
histo + geom_histogram(aes(y = ..density..), fill = "white", colour = "black", binwidth = ((max(study$VOT[study$Word==word])-min(study$VOT[study$Word==word]))/10)) + labs(x = "VOT (ms)", y = "Density", title = word) + stat_function(fun = dnorm, args = list(mean = mean(study$VOT[study$Word==word], na.rm=T), sd = sd(study$VOT[study$Word==word], na.rm = T)), colour = "blue", size = 1)
}
I know the for-loop is working correctly, because when I put print()
around that last very long line starting with histo + ...
, I see it printing my eight histograms in succession, overwriting each other. When I don't write print()
(like in the above code), nothing is printed.
My question is simple: how can I stop my histograms from overwriting each other, and have them together in one picture?
Upvotes: 1
Views: 821
Reputation: 6545
How about using facet_wrap
instead of a for loop?
set.seed(1)
study <- mtcars
study$Word <- sample(1:8, nrow(study), replace = TRUE)
study$VOT <- study$mpg
p <- ggplot(study, aes(x = VOT, y = ..density..)) + geom_histogram()
p <- p + facet_wrap(~ Word, nrow = 4, ncol = 2)
Upvotes: 3