将“整体”组添加到facet_wrap(ggplot2)

问题描述 投票:0回答:1

我的数据中有两组,A1和A2。每组有约50%的男性和大致正常的年龄分布。我想绘制每组中年龄分布的直方图,按性别和按性别划分的总体年龄分布(也可能是无性别的?)。age vs. density

有没有办法用facet_wrap做到这一点?如果没有,有没有办法可以操作我的数据(例如添加一个虚拟变量)并添加它?

r ggplot2 markdown facet-grid
1个回答
1
投票

假设你有:

library(tidyverse)
ggplot(iris, 
       aes(Sepal.Length, fill = Sepal.Width > 3)) + 
  geom_histogram() +
  facet_wrap(~Species)

enter image description here

您可以操纵数据以包含数据集的另一个副本,其中“物种”始终为“总数”。然后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)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.