Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 - Graph with line and dots for two data sets legend issues

I'm graphing two data sets with ggplot. One should be a line, the other should be points. I can get this working as below:

d1 <- filter(d, variable==lineVar)
d2 <- filter(d, variable==dotVar)
g <- ggplot(d1, aes(clarity, x=xv, y=yv))
g <- g + geom_line(aes(colour=variable))
g <- g + ggtitle(title)
g <- g + xlab(xl)
g <- g + ylab(yl)
g <- g + geom_point(data=d2, size=4, aes(colour=variable))

Output of ggplot2

The only issue is the legend! As you can see, the "observed" data set has a line + point in the legend, when it really should just be a point. And reverse for "predicted", it should just be a line.

Is there some way to get a cleaner / more accurate legend?

like image 902
David Terei Avatar asked Sep 26 '15 00:09

David Terei


1 Answers

You can change the legend without changing the plot by using override.aes. You didn't provide sample data, so I've used the built-in mtcars data frame for illustration. The key line of code begins with guides. shape=c(16,NA) gets rid of one of the legend's point markers by setting its colour to NA. linetype=c(0,1) gets rid of the other legend's line by setting its linetype to 0. Also, you don't need to save the plot after each line of code. Just add a + to each line and string them all together in a single statement, as in the example below.

library(reshape2)
library(ggplot2)

mtcars$mpg.line = mtcars$mpg
mtcars.m = melt(mtcars[,c("mpg","mpg.line","wt")], id.var="wt")
mtcars.m$variable = factor(mtcars.m$variable)

ggplot() +
  geom_line(data=mtcars.m[mtcars.m$variable=="mpg.line",],
             aes(wt, value, colour=variable), lwd=1) +
  geom_point(data=mtcars.m[mtcars.m$variable=="mpg",],
             aes(wt, value, colour=variable), size=3) +
  guides(colour=guide_legend(override.aes=list(shape=c(16,NA), linetype=c(0,1)))) +
  theme_grey(base_size=15)

enter image description here

like image 58
eipi10 Avatar answered Sep 23 '22 11:09

eipi10