1
votes

I have a data frame:

df<-data.frame(Pet=rep(c("Dog", "Cat", "Bird"), c(5,10,15)), Gen=rep(c("M", "F", "M", "F", "M", "F"), c(3,5,12,5,3,2)))

As I visualize the frequency of male/female for each animals I get this graph:

ggplot(df, aes(Pet, group=Gen, fill=Gen)) + geom_bar(position="dodge", width=.5)

How do I make a graph that would have bars for females with same height and the bars for males with relative height to the corresponding female bars?

Something like this: Something like this

1

1 Answers

1
votes

An easy fix would be to normalize the data firstly, then do the plot:

t = table(df)
as.data.frame.table(t/t[,'F']) %>% 
    ggplot(aes(x=Pet, y=Freq, group=Gen, fill=Gen)) + 
    geom_bar(position="dodge", width=.5, stat="identity")

enter image description here