plot - R ggplot2 stacked barplot normalized by the value of a column -
i have following dataframe t
:
name type total 1 20 1 20 3 20 2 20 3 20 b 1 25 b 2 25 c 5 35 c 5 35 c 6 35 c 1 35
the total
identical entries same name
. want plot stacked barplot type
on x axis
, count of name
normalized total
on y axis
. plotted non normalized plot following :
ggplot(t, aes(type,fill= name))+geom_bar() + geom_bar(position="fill")
how can plot normalized barplot ? i.e type = 1
y axis value 2/20
a
, 1/25
b
, 1/35
c
...
my try did not work:
ggplot(t, aes(type, ..count../t$total[1],fill= name))+geom_bar() + geom_bar(position="fill")
read in data
d <- read.table(header = true, text = 'name type total 1 20 1 20 3 20 2 20 3 20 b 1 25 b 2 25 c 5 35 c 5 35 c 6 35 c 1 35')
it's bad idea call t
, since name of transpose function.
calculate fractions
library(dplyr) d2 <- d %>% group_by(name, type) %>% summarize(frac = n() / first(total))
this easier using dplyr
package.
make plot
ggplot(d2, aes(type, frac, fill = name)) + geom_bar(stat = 'identity')
Comments
Post a Comment