【问题标题】:create a histogram with female sex for two groups in ggplot r在 ggplot r 中为两组女性创建直方图
【发布时间】:2020-04-12 23:37:26
【问题描述】:

我想创建一个直方图,显示每个年龄组(x 轴)的女性比例(y 轴)。我想为每个年龄组设置两个条形图,分别代表患有“N”病和未患“N”病的女性。

数据:

我查看过的与该主题相关的其他帖子:

r percentage by bin in histogram ggplot

Barplots with multiple factor groupings and mean of variable across those factors

我尝试过的代码:

ggplot(N_group, aes(x=Age_2, fill=Sex))+
  geom_bar(aes( y=..count../tapply(..count.., ..x.. ,sum)[..x..]), position="dodge" ) +
  geom_text(aes( y=..count../tapply(..count.., ..x.. ,sum)[..x..], 
label=scales::percent(..count../tapply(..count.., ..x.. ,sum)[..x..]) ),
            stat="count", position=position_dodge(0.9), vjust=-0.5)

这比较了患有“N”病的男性和女性。

【问题讨论】:

  • 你看过这个post。原因,问的 Q 是不可重现的。请不要发布数据截图。

标签: r ggplot2 histogram geom-bar


【解决方案1】:

在这里,一个可能的解决方案是计算ggplot2 之外的比例。

这里是一个使用以下假数据框的示例:

df <- data.frame(ID = 1:40,
                 N = sample(c(0,1),40,replace = TRUE),
                 age_group = sample(1:4,40, replace = TRUE),
                 sex = sample(c("M","F"),40,replace = TRUE))

使用dplyr包,你可以计算每个性别每个age_group的每个N组的比例:

library(dplyr)

df %>% 
  #group_by(sex, age_group, N, .drop = FALSE) %>% 
  count(sex, age_group, N) %>% 
  filter(sex =="F") %>%
  group_by(age_group) %>%
  mutate(Percent = n / sum(n))


# A tibble: 8 x 5
# Groups:   age_group [4]
  sex   age_group     N     n Percent
  <fct>     <int> <dbl> <int>   <dbl>
1 F             1     0     1   0.167
2 F             1     1     5   0.833
3 F             2     0     2   0.4  
4 F             2     1     3   0.6  
5 F             3     0     2   0.4  
6 F             3     1     3   0.6  
7 F             4     0     1   0.5  
8 F             4     1     1   0.5 

将此管道序列传递给ggplot2 会得到以下图表:

library(dplyr)
library(ggplot2)

df %>% 
  count(sex, age_group, N) %>% 
  filter(sex =="F") %>%
  group_by(age_group) %>%
  mutate(Percent = n / sum(n)) %>%
  ggplot(aes(x = age_group, y = Percent, fill = factor(N)))+
  geom_col(position = position_dodge())+
  scale_y_continuous(labels = scales::percent)

它回答了你的问题吗?

【讨论】:

  • 谢谢@dc37 我的代码出现了这个错误(包括你的数据和我的数据)计数错误(。,性别,年龄组,N):未使用的参数(N)
  • 很奇怪,因为在我的例子中,我没有这个问题。一切运行顺利。你能显示str(df)的输出吗?
猜你喜欢
  • 2020-08-18
  • 2017-11-11
  • 1970-01-01
  • 1970-01-01
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多