簡體   English   中英

R:ggplot2 二項式結果的條形圖

[英]R: ggplot2 Barplot for binomial outcome

我想用 ggplot2 創建一個條形圖,繪制二項式結果的百分比。 這是我擁有的數據:

IndividualID         Pass               Group
001                  Yes                Group1
002                  Yes                Group1
003                  No                 Group1
004                  Yes                Group2
005                  No                 Group2
006                  No                 Group2
007                  Yes                Group3
008                  Yes                Group3
009                  Yes                Group3

理想情況下,我想創建類似於此圖的內容(從不同的數據集創建):

在此處輸入圖片說明

編輯:我嘗試了以下但沒有運氣。

p<-ggplot(data=data, aes(x=Group, y=Pass)) +
  geom_bar(stat="identity", position = 'fill', fill="steelblue")+
  scale_y_continuous(labels = scales::percent)

在 ggplot 中必須有一種直接的方法來做到這一點,但這里有一種在繪圖前准備數據的方法。

library(dplyr)
library(ggplot2)

df %>%
  count(Group, Pass) %>%
  group_by(Group) %>%
  mutate(n = n/sum(n) * 100) %>%
  ggplot() + aes(Group, n, fill = Pass, label = paste0(round(n, 2), "%")) + 
  geom_col() +
  geom_text(position=position_stack(0.5))

在此處輸入圖片說明

數據

df <- structure(list(IndividualID = 1:9, Pass = structure(c(2L, 2L, 
1L, 2L, 1L, 1L, 2L, 2L, 2L), .Label = c("No", "Yes"), class = "factor"), 
Group = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("Group1", 
"Group2", "Group3"), class = "factor")), class = "data.frame",row.names = c(NA,-9L))

暫無
暫無

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

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