簡體   English   中英

ggplot geom_bar 按組和 facet_wrap 繪制百分比

[英]ggplot geom_bar plot percentages by group and facet_wrap

我想在一個圖表上繪制多個類別,每個類別的百分比加起來為 100%。 例如,如果我繪制男性與女性的圖,則每個分組(男性或女性)加起來為 100%。 我正在使用以下代碼,其中百分比似乎適用於兩個圖表上的所有組,即如果您將左側和右側圖表上的所有條形加起來,它們的總和將為 100%,而不是黃色條形上的左側圖表總計 100%,左側圖表上的紫色條總計 100% 等。

我很欣賞這可以通過使用 stat = 'identity' 來實現,但是有沒有一種方法可以在 ggplot 中做到這一點,而無需在繪圖之前對數據框進行處理?

library(ggplot2)  

tmp <- diamonds %>% filter(color %in% c("E","I")) %>% select(color, cut, clarity)

ggplot(data=tmp,
     aes(x=clarity,
         fill=cut)) + 
  geom_bar(aes(y = (..count..)/sum(..count..)), position="dodge") +
  scale_y_continuous(labels = scales::percent) + facet_wrap(vars(color))

在此處輸入圖片說明

在計算 ggplot2 中的百分比時,您必須像在將數據傳遞給 ggplot 之前匯總數據時那樣對數據進行分組。 在您的情況下,由 ggplot2 在內部添加到數據的PANEL列可用於分組:

使用after_stattapply可以這樣實現:

library(ggplot2)  
library(dplyr)

tmp <- diamonds %>% filter(color %in% c("E","I")) %>% select(color, cut, clarity)

ggplot(data=tmp,
       aes(x=clarity,
           fill=cut)) + 
  geom_bar(aes(y = after_stat(count/tapply(count, PANEL, sum)[PANEL])), position="dodge") +
  scale_y_continuous(labels = scales::percent) + facet_wrap(vars(color))

或者使用..符號:

ggplot(data=tmp,
       aes(x=clarity,
           fill=cut)) + 
  geom_bar(aes(y = ..count../tapply(..count.., ..PANEL.., sum)[..PANEL..]), position="dodge") +
  scale_y_continuous(labels = scales::percent) + facet_wrap(vars(color))

編輯如果您需要按多個變量分組,我建議使用輔助函數,在該函數中我使用dplyr進行計算:

comp_pct <- function(count, PANEL, cut) {
  data.frame(count, PANEL, cut) %>% 
    group_by(PANEL, cut) %>% 
    mutate(pct = count / sum(count)) %>% 
    pull(pct)
}

ggplot(data=tmp,
       aes(x=clarity,
           fill=cut)) + 
  geom_bar(aes(y = after_stat(comp_pct(count, PANEL, fill))), position="dodge") +
  scale_y_continuous(labels = scales::percent) + facet_wrap(vars(color))

暫無
暫無

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

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