I have the following dataframe 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.
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.
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 ? i.e for type = 1 the y axis value would be 2/20 for a and 1/25 for b and 1/35 for 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.
library(dplyr)
d2 <- d %>%
group_by(name, type) %>%
summarize(frac = n() / first(total))
This is much easier to do using the dplyr package.
ggplot(d2, aes(type, frac, fill = name)) +
geom_bar(stat = 'identity')

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With