R – problem with legend while plotting data from two data.frame

ggplot2r

I'm having a little trouble with getting ggplot2 to work as I want. Basically, I'd like to compare actual observations vs. approximated by putting them in one single plot. For example,

> library(ggplot2)
> df.actual <- data.frame(x = 1:100, y = (1:100) * 2)
> df.approx <- data.frame(x = 1:150, y = (1:150) * 2 + 5  + rnorm(150, mean = 3) )
> ggplot() + geom_point(aes(x, y), data = df.actual) + geom_line(aes(x,y), data = df.approx)

My problem is that I can't display a legend. I read somewhere that ggplot2's legend is not very flexible(?). Ideally, a legend with

  • title = 'Type'
  • key: a black filled point, and a black line
  • key label: 'Actual', 'Approximate'
  • legend.position = 'topright'

Thanks.

Best Solution

Try this to get you started

ggplot() + 
  geom_point(aes(x, y, colour = "actual"), data = df.actual) + 
  geom_line(aes(x, y, colour = "approximate"), data = df.approx) + 
  scale_colour_discrete("Type")
Related Question