如何按特定组在 R 分组中生成百分比条形图?

How can I produce a percentage barchart in R groupping by specific group?

我在 R 中有这样一个 table:

Name Column2 Counts
Jason Disease 5
Jason NonDisease 6
Jason Iduced 7
Giacomo Disease 2
Giacomo NonDisease 2
Giacomo Induced 6

我想制作一个类似这样的情节 但是我想要名字而不是“日”而不是“性别”我会根据疾病分组并计算按数据框的第 3 列分组的计数百分比,所以例如我想要2 条名为 Jason 和 Giacomo(而不是当天的名称)的百分比根据第三列计算,例如 Jason,Disease = 5/(5+6+7),Giacomo Disease,2/(2+2+ 6) 以此类推其他网格中的其他条件(而不是性别)(非疾病和诱导的计算相同)。

为了生成上面的图,我使用了以下代码和数据集

library(tidyverse)
data(tips, package = "reshape2")

  ggplot(tips, aes(x= day,  group=sex)) + 
  geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") +
  geom_text(aes( label = scales::percent(..prop..),
                 y= ..prop.. ), stat= "count", vjust = -.5) +
  labs(y = "Percent", fill="day") +
  facet_grid(~sex) +
  scale_y_continuous(labels = scales::percent)

好的,数据与您的示例不完全匹配,但我相信您要了解的是如何切换哪个变量被分解成组,哪个变量被分面。您可以在 xgroup 美学中更改它们,以及 facet_grid 中的变量以进行您可能喜欢的任何组合。例如,要在每一天显示 male/female,您可以使用此代码:

library(tidyverse)
data(tips, package = "reshape2")

ggplot(tips, aes(x= sex,  group=day)) + 
  geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") +
  geom_text(aes( label = scales::percent(..prop..),
                 y= ..prop.. ), stat= "count", vjust = -.5) +
  labs(y = "Percent", fill="sex") +
  facet_grid(~day) +
  scale_y_continuous(labels = scales::percent)

结果:

据我所知,让我重现代码

name <- c("Jason","Jason","Jason","giamco","giamco","giamco")
disease <- c("Disease","NonDisease","Iduced","Disease","NonDisease","Iduced")
Counts <- c(5,6,7,2,2,6)
df <- data.frame(name,disease,Counts)

此代码将产生您的要求:

df %>% group_by(name) %>% mutate(sum_num = sum(Counts)) %>% ggplot(aes(x = name, y = 
Counts, fill = disease))+geom_bar(stat = "identity",position = position_dodge(width = 
0.9))+geom_text(aes(label = paste0(round(Counts/sum_num * 100,0),"%")), position = 
position_dodge(width = 0.9),vjust = -0.9)

结果: