I look at creating a faceted histogram in a loop. The problem occurs when I call facet_wrap in a loop. I tried different options, but they all failed with the following message:
Mistake in layout_base (data, vars, drop = drop): at least one layer must contain all the variables used for faceting
The following is a reproducible example.
library(ggplot2)
library(scales)
datatest <- data.frame(
column1 = sample(c("yes", "no"), 50, replace = TRUE),
column2 = sample(c("yes", "no"), 50, replace = TRUE),
column3 = sample(c("yes", "no"), 50, replace = TRUE),
column4 = sample(c("yes", "no"), 50, replace = TRUE)
)
rand.date=function(start.day,end.day,data){
size=dim(data)[1]
days=seq.Date(as.Date(start.day),as.Date(end.day),by="day")
pick.day=runif(size,1,length(days))
date=days[pick.day]
}
datatest$date=rand.date("2016-01-01","2016-09-21",datatest)
histotest <- ggplot(datatest, aes(x = date)) +
geom_histogram(binwidth = 7, fill="#2a87c8", colour="white") +
scale_x_date(limits = c(Sys.Date() - 250, NA), labels = date_format("%b %Y")) +
labs(x = "Period", y = "Count") +
facet_wrap(~ column1 , ncol=1) +
theme(plot.title=element_text(face="bold", size=9),
panel.grid.major = element_line(colour = "white"),
panel.grid.minor = element_blank())
ggsave("out/column1_histo.png", plot=histotest, width=12, height=6,units="in", dpi=300)
This is where the problem arises:
for (i in 1:4 ) {
rm(variablename)
variablename <- names(datatest)[i]
histoloop <- ggplot(datatest, aes(x = date)) +
geom_histogram(binwidth = 7, fill="#2a87c8", colour="white") +
scale_x_date(limits = c(Sys.Date() - 250, NA), labels = date_format("%b %Y")) +
labs(x = "Period", y = "Count") +
facet_wrap(~ variablename , ncol=1) +
theme(plot.title=element_text(face="bold", size=9),
panel.grid.major = element_line(colour = "white"),
panel.grid.minor = element_blank())
ggsave(filename=paste("out/",variablename,"_histo.png",sep=""), plot=histoloop, width=12, height=6,units="in", dpi=300)
}