[R] ggplot grouped barchart based on marginal proportions

Paul Sanfilippo prseye at gmail.com
Tue Sep 27 01:04:25 CEST 2016


I am trying to create a grouped barplot that uses marginal (row) proportions rather than cell proportions and can't figure out how to change:

y = (..count..)/sum(..count..)
in ggplot to do this.

Using the mtcars dataset as an example and considering two categorical variables (cyl and am - purely for the sake of the example taking cyl as the response and am as the explanatory variable). Can anyone help me to do this:

data(mtcars)
# Get Proportions
mtcars_xtab <- table(mtcars$cyl,mtcars$am)
mtcars_xtab
margin.table(mtcars_xtab, 1) # A frequencies (summed over B) 
margin.table(mtcars_xtab, 2) # B frequencies (summed over A)
prop.table(mtcars_xtab) # cell percentages - THIS IS WHAT'S USED IN THE PLOT
prop.table(mtcars_xtab, 1) # row percentages - THESE ARE WHAT I WANT TO USE IN THE PLOT

# Make Plot
mtcars$cyl <- as.factor(mtcars$cyl) 
mtcars$am <- as.factor(mtcars$am) 
ggplot(mtcars, aes(x=am, fill=cyl)) +
geom_bar(aes(y = (..count..)/sum(..count..)), position = "dodge") +
  scale_fill_brewer(palette="Set2")
Thank you.




	[[alternative HTML version deleted]]



More information about the R-help mailing list