我的数据中有两组,A1和A2。每组有约50%的男性和大致正常的年龄分布。我想绘制每组中年龄分布的直方图,按性别和按性别划分的总体年龄分布(也可能是无性别的?)。
有没有办法用facet_wrap做到这一点?如果没有,有没有办法可以操作我的数据(例如添加一个虚拟变量)并添加它?
假设你有:
library(tidyverse)
ggplot(iris,
aes(Sepal.Length, fill = Sepal.Width > 3)) +
geom_histogram() +
facet_wrap(~Species)
您可以操纵数据以包含数据集的另一个副本,其中“物种”始终为“总数”。然后geom_histogram
将使用完整数据集作为对应于“总计”的方面。
ggplot(iris %>%
bind_rows(iris %>% mutate(Species = "total")),
aes(Sepal.Length, fill = Sepal.Width > 3)) +
geom_histogram() +
# I want 'total' at the end
facet_wrap(~fct_relevel(Species, "total", after = Inf), nrow = 1)