1
votes

I plotted two ggplots from two different datasets in one single plot. plots are simple linear regression. I want to add legend both for lines and dots in the plot with different colours. How can I do that? The code I used for plot is as below. But, I failed to add a desirable legend to that.

ggplot() + 
     geom_point(aes(x = Time_1, y = value1)) +
     geom_point(aes(x = Time_2, y = value2)) +
     geom_line(aes(x = Time_1, y = predict(reg, newdata = dataset)))+
     geom_line(aes(x = Time_Month.x, y = predict(regressor, newdata = training_set)))+ 
     ggtitle('Two plots in a single plot')

1

1 Answers

2
votes

ggplot2 adds legends automatically if it has groups within the data. Your original code provides the minimum amount of information to ggplot(), basically enough for it to work but not enough to create a legend.

Since your data comes from two different objects due to the two different regressions, then it looks like all you need in this case is to add the 'color = "INSERT COLOR NAME"' argument to each geom_point() and each geom_line(). Using R's built-in mtcars data set for example, what you have is similar to

ggplot(mtcars) + geom_point(aes(x = cyl, y = mpg)) + geom_point(aes(x = cyl, y = wt)) + ggtitle("Example Graph")

Graph without Legend

And what you want can be obtained by using something similar to,

ggplot(mtcars) + geom_point(aes(x = cyl, y = mpg, color = "blue")) + geom_point(aes(x = cyl, y = wt, color = "green")) + ggtitle("Example Graph")

Graph with Legend

Which would seem to translate to

ggplot() + 
 geom_point(aes(x = Time_1, y = value1, color = "blue")) +
 geom_point(aes(x = Time_2, y = value2, color = "green")) +
 geom_line(aes(x = Time_1, y = predict(reg, newdata = dataset), color = "red"))+
 geom_line(aes(x = Time_Month.x, y = predict(regressor, newdata = training_set), color = "yellow"))+ 
 ggtitle('Two plots in a single plot')

You could also use the size, shape, or alpha arguments inside of aes() to differentiate the different series.