Legends for separate lines and points

174 views
Skip to first unread message

willem vervoort

unread,
Jun 23, 2010, 8:05:49 AM6/23/10
to ggp...@googlegroups.com
I am relatively new to ggplot2 and I don't seem to be able to find an answer to how you create a legend if you plot two different y values in a plot.
Here is some example code similar to what I am trying to do
library(ggplot2)

x <- rep(runif(20),5)
y <- rnorm(100)
y2 <- mean(y) + sd(y)*x
treat <- ifelse(x > 0.5, "treat 1","treat 2")
crop <- ifelse(y > 0,"Fallow","Crop")

plot.frame <- data.frame(x = x, y = y, y2 = y2, treat = treat,
      crop = crop)
     
p <- ggplot(plot.frame, aes(x=x,y=y)) +
      geom_point(size=2,colour="black") +
      geom_line(aes(x=x,y=y2,colour="red"),colour="red",size=1) +
      facet_grid(crop~treat) +
      opts(labels = c(x = "Variable 1", y = "Variable 2"))

print(p)


I would like to have a legend next to the plot that says:
Legend title
"Points name"
"Line name"

I have searched through all the posts, but have not managed to figure it out. Any help is appreciated.
Regards
Willem
--
http://blogs.usyd.edu.au/waterhydrosu/

Willem

unread,
Jun 24, 2010, 1:38:04 AM6/24/10
to ggplot2
Found part of the answer myself, but I still can't get the points in
the legend. However, now I have got a legend for the line
Willem

library(ggplot2)

x <- rep(runif(20),5)
y <- rnorm(100)
y2 <- mean(y) + sd(y)*x
treat <- ifelse(x > 0.5, "treat 1","treat 2")
crop <- ifelse(y > 0,"Fallow","Crop")

plot.frame <- data.frame(x = x, y = y, y2 = y2, treat = treat,
crop = crop)

p <- ggplot(plot.frame, aes(x=x,y=y)) +
geom_point(size=2,colour="black") +
geom_line(aes(x=x,y=y2,colour="line"),size=1) +
facet_grid(crop~treat) +
opts(labels = c(x = "Variable 1", y = "Variable 2"))
p <- p + scale_colour_manual("Adjust",c("black"="black","line"="red"))

print(p)

Hadley Wickham

unread,
Jun 24, 2010, 9:32:31 AM6/24/10
to Willem, ggplot2
Hi Willem,

You were so close:

p <- ggplot(plot.frame, aes(x=x,y=y)) +

geom_point(aes(colour = "point"), size=2) +


geom_line(aes(x=x,y=y2,colour="line"),size=1) +
facet_grid(crop~treat) +
opts(labels = c(x = "Variable 1", y = "Variable 2"))

p <- p + scale_colour_manual("Adjust",c("point"="black","line"="red"))

Unfortunately the legend can't currently tell you only have red points
and black lines, but it's something I hope to fix in a future release.

Hadley

> --
> You received this message because you are subscribed to the ggplot2 mailing list.
> Please provide a reproducible example: http://gist.github.com/270442
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2
>

--
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/

Reply all
Reply to author
Forward
0 new messages