[英]R ggplot2 stacked barplot normalized by the value of a column
我有以下數據幀t
:
name type total
a 1 20
a 1 20
a 3 20
a 2 20
a 3 20
b 1 25
b 2 25
c 5 35
c 5 35
c 6 35
c 1 35
對於具有相同name
所有條目, total
是相同的。 我想繪制一個堆積的條形圖,其中x axis
type
和count of name
由y axis
的total
標准化。 我通過以下方式繪制了非標准化圖 :
ggplot(t, aes(type,fill= name))+geom_bar() + geom_bar(position="fill")
如何繪制標准化的條形圖 ? 即,對於type = 1
y軸值將是2/20
為a
和1/25
為b
和1/35
為c
...
我的嘗試不起作用:
ggplot(t, aes(type, ..count../t$total[1],fill= name))+geom_bar() + geom_bar(position="fill")
d <- read.table(header = TRUE, text =
'name type total
a 1 20
a 1 20
a 3 20
a 2 20
a 3 20
b 1 25
b 2 25
c 5 35
c 5 35
c 6 35
c 1 35')
將其稱為t
是一個壞主意,因為這是轉置函數的名稱。
library(dplyr)
d2 <- d %>%
group_by(name, type) %>%
summarize(frac = n() / first(total))
使用dplyr
包更容易。
ggplot(d2, aes(type, frac, fill = name)) +
geom_bar(stat = 'identity')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.