簡體   English   中英

R ggplot2堆積的條形圖通過列的值進行歸一化

[英]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 typecount of namey axistotal標准化。 我通過以下方式繪制了非標准化圖

ggplot(t, aes(type,fill= name))+geom_bar() + geom_bar(position="fill")

如何繪制標准化的條形圖 即,對於type = 1 y軸值將是2/20a1/25b1/35c ...

我的嘗試不起作用:

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.

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