[英]R ggplot2 stacked barplot normalized by the value of a column
I have the following dataframe t
: 我有以下数据帧
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
The total
is the identical for all the entries with the same name
. 对于具有相同
name
所有条目, total
是相同的。 I want to plot a stacked barplot with type
on the x axis
and count of name
normalized by the total
on the y axis
. 我想绘制一个堆积的条形图,其中
x axis
type
和count of name
由y axis
的total
标准化。 I plotted the non normalized plot by the following : 我通过以下方式绘制了非标准化图 :
ggplot(t, aes(type,fill= name))+geom_bar() + geom_bar(position="fill")
How can I plot the normalized barplot ? 如何绘制标准化的条形图 ? ie for
type = 1
the y axis value would be 2/20
for a
and 1/25
for b
and 1/35
for c
... 即,对于
type = 1
y轴值将是2/20
为a
和1/25
为b
和1/35
为c
...
My try which did not work: 我的尝试不起作用:
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')
It's a bad idea to call it t
, since that is the name of the transpose function. 将其称为
t
是一个坏主意,因为这是转置函数的名称。
library(dplyr)
d2 <- d %>%
group_by(name, type) %>%
summarize(frac = n() / first(total))
This is much easier to do using the dplyr
package. 使用
dplyr
包更容易。
ggplot(d2, aes(type, frac, fill = name)) +
geom_bar(stat = 'identity')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.