Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: barplot of fractions of single level of the factor in each bin

For example we have usual stacked bar plot:

ggplot(diamonds, aes(x=color, fill=cut))+geom_bar(position="fill")

enter image description here

And I want to make same plot but leave on it only one of "Cut" - types. For example "Ideal" (purple one). Thus, it should be something like histogram of fraction of the Ideal diamonds among all other diamonds having same color. Can I do this within ggplot?

like image 211
yerba Avatar asked Oct 25 '25 05:10

yerba


1 Answers

If you pre-summarize the data, it is straightforward:

library("plyr")

idl <- ddply(diamonds, .(color), summarize, 
             idealpct = sum(cut=="Ideal")/length(cut))

ggplot(idl, aes(x=color, y=idealpct)) + 
  geom_bar()

enter image description here

like image 115
Brian Diggs Avatar answered Oct 26 '25 19:10

Brian Diggs