[英]R stacked percentage bar plot with percentage of binary factor and labels (with ggplot)
[英]R Stacked percentage bar plot with percentage of two factor variables with ggplot
我試圖繪制兩個因子變量,並在圖中用 % 標記結果。
我已經檢查了這篇文章和他/她提供的鏈接:
您在這里看到的 ggplot 行實際上來自推薦的帖子之一:
sex <- c("F","F","M", "M", "M", "F","M","F","F", "M", "M", "M", "M","F","F", "M", "M", "F")
behavior <- c("A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C", "B", "C", "A")
BehSex <- data.frame(sex, behavior)
ggplot(BehSex, aes(x= factor(sex), fill= factor(behavior), y = (..count..)/sum(..count..)))+
geom_bar() +
stat_bin(geom = "text",
aes(label = paste(round((..count..)/sum(..count..)*100), "%")),
vjust = 5)
但是,當我使用該行時,出現以下錯誤:
錯誤:StatBin 需要一個連續的 x 變量:x 變量是離散的。 也許你想要 stat="count"?
我嘗試在 geom_bar() 中使用 stat="count" 但它似乎沒有按預期工作。
三個問題:
1)我做錯了什么?
2)我怎樣才能繪制出我想要的圖?
3)我如何繪制:百分比,然后在另一個圖中繪制計數?
這是我現在的情節
預先感謝您的幫助!
關於您提到的帖子的答案,您必須使用position = position_stack()
顯示百分比。
此外,您可以使用dplyr
包從數據dplyr
獲取百分比。 在我看來,顯示標簽更容易:
library(dplyr)
df <- BehSex %>% group_by(sex) %>% count(behavior) %>% mutate(Percent = n / sum(n)*100)
# A tibble: 6 x 4
# Groups: sex [2]
sex behavior n Percent
<fct> <fct> <int> <dbl>
1 F A 2 25
2 F B 3 37.5
3 F C 3 37.5
4 M A 4 40
5 M B 3 30
6 M C 3 30
然后,你可以像這樣得到你的情節:
ggplot(df, aes(x = sex, y = Percent, fill = behavior))+
geom_bar(stat = "identity")+
geom_text(aes(label = paste(Percent,"%"), y = Percent),
position = position_stack(vjust = 0.5))+
coord_flip()+
labs(x = "Sex", y = "Percentage",fill = "Behavior")
這是使用dplyr
進行一些數據准備的另一種方法:
編輯:添加計數。 要顯示其中一個,只需更改標簽即可。
library(dplyr)
BehSexSum <- BehSex %>%
count(sex, behavior) %>%
mutate(pct = n / sum(n),
pct_label = scales::percent(pct))
ggplot(BehSexSum, aes(x= sex, fill = behavior, y = pct)) +
geom_col() +
geom_text(aes(label = paste(pct_label, n, sep = "\n")),
lineheight = 0.8,
position = position_stack(vjust = 0.5)) +
scale_y_continuous(labels = scales::percent)
我認為將 y 軸標簽格式化為百分比的更簡單方法是使用scale_y_continuous(labels = scales::percent)
,而不是使用stat_bin(...)
。 因此,代碼幾乎可以保持不變。
ggplot(BehSex, aes(x= factor(sex), fill= factor(behavior), y =(..count..)/sum(..count..)))+
geom_bar() +
#Set the y axis format as percentage
scale_y_continuous(labels = scales::percent)+
#Change the legend and axes names
labs(x = "Sex", y = "Percentage",fill = "Behavior")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.