[R] ggplot2 legend problem

Chris Friedl cfriedalek at gmail.com
Wed Aug 19 04:10:11 CEST 2009

I'm trying to overlay two histograms using transparency to enable viewing of
multiple distributions on a single scale. So far ggplot2 seems to do what I
want. However I'm having a problem generating the legend coloring
appropriate to each distribution in the plot.

Here is a test case to show my best (failed) effort so far:

x <- data.frame(X=rnorm(1000, mean=0))
y <- data.frame(Y=rnorm(1000, mean=3))
xy <- cbind(x, y)
g <- ggplot(xy)
g + geom_histogram(aes(x=X), colour="black", binwidth = 0.1, fill =
alpha("red", .5)) +
    geom_histogram(aes(x=Y), colour="black", binwidth = 0.1, fill =
alpha("blue", .5)) +
    scale_fill_manual("Case", values = alpha(c("red","blue"), 0.5),
limits=c("A", "B")) +
    opts(title = "A & B distributions") +

The plot is just what I want and looks gorgeous on my screen. However the
legend boxes labeled "A" and "B" respectively have no color and I have tried
many variations to get legend color, to no avail.

Based on what I could discern from the manual I thought this scale_ command
might work:

    scale_fill_manual("Case", c("A" = alpha("red", 0.5),
"B"=alpha("blue",0.5))) +

However in this case I get no legend at all.

I've spent hours on this and now I'm "dazed and confused". Hope someone can
help me "through this land of confusion" .... (OK, some old song lyrics
popped into my head ... )



View this message in context: http://www.nabble.com/ggplot2-legend-problem-tp25036665p25036665.html
Sent from the R help mailing list archive at Nabble.com.

More information about the R-help mailing list