[R] ggplot2: legend

Thaler,Thorn,LAUSANNE,Applied Mathematics Thorn.Thaler at rdls.nestle.com
Tue Jul 3 18:50:52 CEST 2012


Dear all,

I produced the following graph with ggplot which is almost fine, yet I don't like that the legend for "Means" and "Observations" includes a line, though no line is used in the plot for those two (the line for "Overall Mean" on the other hand is wanted):

library(ggplot2)
ddf <- data.frame(x = factor(rep(LETTERS[1:2], 5)), y = rnorm(10)) 
p <- ggplot(ddf, aes(x = x, y = y))
p + geom_point(aes(colour="Observations", shape="Observations")) +
    stat_summary(aes(colour = "Means", shape ="Means"), 
                 fun.y = mean, fun.ymin = min, fun.ymax = max, 
                 geom = "point") +
    geom_hline(aes(yintercept = mean(y), linetype = "Overall Mean"), show_guide = TRUE)

I tried to map the linetype in geom_point (and stat_summary) to NULL and I tried to set it to "blank" but neither worked.

Is it furthermore possible to combine the two legends? My preferred plot would have two symbols with different colours and shapes for "Means" and "Observations" (but no line) and directly below that a line for "Overall Mean" (that is all the three items in one legend)? For that I tried to assign the same names to the legends but this did not work either.

So any help would be highly appreciated.

Kind Regards,

Thorn Thaler
Mathematician

Applied Mathematics 
Nestec Ltd,
Nestlé Research Center
PO Box 44 
CH-1000 Lausanne 26
Phone: +41 21 785 8220
Fax: +41 21 785 9486



More information about the R-help mailing list