Ggplot2 - Graph with line and points for two dataset tasks

I am drawing two datasets using ggplot. It needs to be a line, the other must be a point. I can make this work as shown 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)) 

Ggplot2 output

The only problem is the legend! As you can see, the “observable” dataset has a row + dot in the legend when it really should be a dot. And vice versa for the "predicted", it should be only a string.

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

+6
source share
1 answer

You can change the legend without changing the schedule using override.aes . You did not provide sample data, so I used the mtcars built-in data mtcars for illustration. The key line of code begins with guides . shape=c(16,NA) gets rid of one of the legend point markers by setting its color to NA . linetype=c(0,1) gets rid of another legend line by setting its line type to 0 . In addition, you do not need to save a graph after each line of code. Just add + to each line and concatenate them all together in one expression, 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

+5
source

All Articles