2

When I use following code to generate a density plot:

require(ggplot2)
set.seed(seed=10)
n <- 10000
s.data <- data.frame(score = rnorm(n,500,100),
                     gender = sample(c("Male","Female","No Response"),size=n,replace=T,prob=c(.4,.55,.05)),
                     major = sample(c("A","B","C","D"),size=n,replace=T,prob=c(.02,.25,.05,.68))) 
ggplot(s.data, aes(major,..density..,fill=major,group=1)) + 
  geom_histogram() + facet_wrap(~ gender)

enter image description here

I cannot distinguish between categories of "major" by color.

What I want to get is density plot similar to this frequency plot in the sense of colors and legend:

ggplot(s.data, aes(major,fill=major)) + 
    geom_histogram() + facet_wrap(~ gender)

enter image description here

This question is following my question (here) which is already answered here.

Community
  • 1
  • 1
HBat
  • 4,873
  • 4
  • 39
  • 56
  • [This SO](http://stackoverflow.com/questions/11773822/fill-colors-in-geom-histogram-density-group-1) question could help – Didzis Elferts May 05 '13 at 15:36
  • I think "density" is reserved for continuous variables. – Frank May 05 '13 at 15:42
  • @DidzisElferts Thanks for comment. I used `ggplot(s.data, aes(x=major, fill = major)) + geom_histogram(aes(y=..count../sum(..count..))) + facet_wrap(~ gender)` But it did not give what I wanted. It just changed the scale of frequency plot. – HBat May 05 '13 at 16:37
  • What if you just pre-calculate everything yourself and just plot the result? – Roman Luštrik May 05 '13 at 17:24

1 Answers1

1

You can still try frequency plot with facet parameter scale="free_y":

ggplot(s.data, aes(major,..count..,fill=major)) + 
  geom_histogram() + facet_wrap(~ gender, scale="free_y")

enter image description here

topchef
  • 19,091
  • 9
  • 63
  • 102
  • Even though it is not direct answer of the question, it solved my problem beautifully. Thank you very much @topchef for showing "scale="free_y"" – HBat May 11 '13 at 18:29