While it seems facet_wrap
does not run the special geom_histogram
percentage calculation within each subset, consider building a list of plots separately and then grid arrange them together.
Specifically, call by
to run your ggplots in subsets of group and then call gridExtra::grid.arrange()
(actual package method) to somewhat mimic facet_wrap
:
library(ggplot2)
library(scales)
library(gridExtra)
...
grp_plots <- by(df, df$group, function(sub){
ggplot(sub, aes(age)) +
geom_histogram(aes(y = (..count..)/sum(..count..)), binwidth = 5) +
scale_y_continuous(labels = percent ) + ggtitle(sub$group[[1]]) +
theme(plot.title = element_text(hjust = 0.5))
})
grid.arrange(grobs = grp_plots, ncol=5)
However to avoid the repeated y-axis and x-axis, consider conditionally setting the theme
within by
call, assuming you know your groups ahead of time and they are a reasonable handful in number.
grp_plots <- by(df, df$group, function(sub){
# BASE GRAPH
p <- ggplot(sub, aes(age)) +
geom_histogram(aes(y = (..count..)/sum(..count..)), binwidth = 5) +
scale_y_continuous(labels = percent ) + ggtitle(sub$group[[1]])
# CONDITIONAL theme() CALLS
if (sub$group[[1]] %in% c("a")) {
p <- p + theme(plot.title = element_text(hjust = 0.5), axis.title.x = element_blank(),
axis.text.x = element_blank(), axis.ticks.x = element_blank())
}
else if (sub$group[[1]] %in% c("f")) {
p <- p + theme(plot.title = element_text(hjust = 0.5))
}
else if (sub$group[[1]] %in% c("b", "c", "d", "e")) {
p <- p + theme(plot.title = element_text(hjust = 0.5), axis.title.y = element_blank(),
axis.text.y = element_blank(), axis.ticks.y = element_blank(),
axis.title.x = element_blank(), axis.text.x = element_blank(),
axis.ticks.x = element_blank())
}
else {
p <- p + theme(plot.title = element_text(hjust = 0.5), axis.title.y = element_blank(),
axis.text.y = element_blank(), axis.ticks.y = element_blank())
}
return(p)
})
grid.arrange(grobs=grp_plots, ncol=5)
geom_histogram(aes(y = stat(width*density)))
– Heelpost