r - ggplot graphing of proportions of observations within categories -


i looking advice on better ways plot proportion of observations in various categories.

i have dataframe looks this:

cat1 <- c("high", "low", "high", "high", "high", "low", "low", "low", "high", "low", "low") cat2 <- c("1-young", "3-old", "2-middle-aged", "3-old", "2-middle-aged", "2-middle-aged", "1-young", "1-young", "3-old", "3-old", "1-young") df <- as.data.frame(cbind(cat1, cat2)) 

in example here, want plot proportion of each age group have value "high", , proportion of each age group have value "low". more generally, want plot, for each value of category 2, percent of observations fall each of levels of category 1.

the following code produces right result, manually counting , dividing before plotting. there way on fly within ggplot?

library(plyr) count1 <- count(df, vars=c("cat1", "cat2")) count2 <- count(df, "cat2")  count1$totals <- count2$freq count1$pct <- count1$freq / count1$totals  ggplot(data = count1, aes(x=cat2, y=pct))+ facet_wrap(~cat1)+ geom_bar() 

this previous stackoverflow question offers similar, following code:

ggplot(mydataf, aes(x = foo)) +  geom_bar(aes(y = (..count..)/sum(..count..))) 

but not want "sum(..count..)" - gives sum of count of all bins - in denominator; rather, want sum of count of each of "cat2" categories. have studied stat_bin documentation.

i grateful tips , suggestions on how make work.

i understand if isn't you're looking for, found description of wanted confusing until realized trying visualize data in way seemed unnatural me.

if asked me produce graph proportions within each category, i'd turn segmented bar chart:

ggplot(df,aes(x = cat2,fill = cat1)) +      geom_bar(position = "fill") 

enter image description here

note y axis records proportions, not counts, wanted.


Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -