Mariya
Mariya

Reputation: 847

R ggplot2 stacked barplot normalized by the value of a column

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")

Upvotes: 3

Views: 2813

Answers (1)

Axeman
Axeman

Reputation: 35377

Read in the data

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.

Calculate the fractions

library(dplyr)
d2 <- d %>% 
  group_by(name, type) %>% 
  summarize(frac = n() / first(total))

This is much easier to do using the dplyr package.

Make the plot

ggplot(d2, aes(type, frac, fill = name)) +
  geom_bar(stat = 'identity')

Result

enter image description here

Upvotes: 3

Related Questions