facet_wrap
不运行特殊
geom_histogram
在每个子集内的百分比计算中,考虑分别构建一个绘图列表,然后将它们排列在一起。
by
在
组
gridExtra::grid.arrange()
小平面U形包装
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)
但是,为了避免重复的y轴和x轴,请考虑有条件地设置
theme
在内部
打电话,假设你提前了解了你的团队,而且他们的人数相当少。
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)