[R] ggplot2 legend problem

hadley wickham h.wickham at gmail.com
Wed Aug 19 14:17:30 CEST 2009


On Tue, Aug 18, 2009 at 11:10 PM, Chris Friedl<cfriedalek at gmail.com> wrote:
>
> Still struggling with this. A further example using a slightly different
> organisation of the data. The factors "A" and "B" are included in the
> dataframe in an attempt to get ggplot to generate a legend automatically.
>
> x <- data.frame(value=rnorm(5000, mean=0), case="A")
> y <- data.frame(value=rnorm(5000, mean=3), case="B")
> xy <- rbind(x, y)
> ggplot(xy, aes(x=value, fill=case, group=case)) +
> geom_histogram(binwidth=0.1)
> ggplot(xy, aes(x=value, fill=case, group=case)) + geom_density(alpha=0.2)
>
> Whilst the legend is generated as expected the histogram and density plots
> are different. The density plots overlap each other whereas the histogram
> plots stack. I'm trying the get the histogram plots to overlap, and retain
> the legend. Is the histogram stacking by design? Can stacking be changed to
> overlapping?

I'm skeptical that this will create a useful plot, but

geom_histogram(binwidth=0.1, position = "identity")

will do what you want.  You might also want to look at geom_freqpoly.

Alternatively, to use your previous approach, you just need to make a
couple of small changes:

g + geom_histogram(aes(x=X, fill = "A"), colour="black", binwidth = 0.1) +
   geom_histogram(aes(x=Y, fill = "B"), colour="black", binwidth = 0.1) +
  scale_fill_manual("Case", c("A" = alpha("red", 0.5), "B"=alpha("blue",0.5)))

Previously you weren't supplying the fill aesthetic so the scale had
nothing to work with.

Hadley

-- 
http://had.co.nz/




More information about the R-help mailing list