簡體   English   中英

如何按特定組在 R 分組中生成百分比條形圖?

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

我在 R 中有這樣的表:

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

我想產生一個與此類似的 plot 但我想使用名稱而不是“性別”而不是“性別”我會根據疾病進行分組並計算按第 3 列分組的計數百分比dataframe,例如,我希望有 2 個名為 Jason 和 Giacomo(而不是當天的名稱)的欄,其百分比是針對第三列計算的,例如 Jason,Disease = 5/(5+6+7) , Giacomo 病, 2/(2+2+6) 等其他網格中的其他條件(而不是性別)(因此對於非疾病和誘導的計算相同)。 在此處輸入圖像描述

為了生成上面的 plot,我使用了以下代碼和數據集

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內部的變量中更改它們以進行您可能喜歡的任何組合。 例如,要每天顯示男性/女性,您可以使用以下代碼:

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)

結果:

圖形

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM