-2

I want to add a legend for the main diagonal and the regression line to the scatter plot.

What I have got now:

library(ggplot2)
df = data.frame(x = 1:10, y = 1:10)

p <- ggplot(df, aes(x, y)) +
geom_point(size=1.2) +
scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
geom_smooth(method="lm", se=FALSE, formula=y~x, colour="blue", fill=NA, size=1.2) +
geom_abline(intercept=0, slope=1, size=1.2, colour="red") +
geom_text(aes(x=max(df[,1])/1.4, y=max(df[,2])/1.2, label=lm_eqn(df)), colour="blue",  parse=TRUE) +
# doesn't work: scale_colour_manual("Lines", labels=c("Main Diagonal", "Regression"), values=c("red", "blue")) +
labs(x="X", y="Y")
Matthias Munz
  • 3,583
  • 4
  • 30
  • 47
  • 3
    This answer really could have been found with some googling. If you use ggplot2 a bit this is a terrific source of information [R Cookbook](http://wiki.stdout.org/rcookbook/Graphs/Legends%20(ggplot2)/) – Tyler Rinker Sep 17 '12 at 14:55
  • lm_eqn is a function that calculates the regression equation. the code can be found here: http://stackoverflow.com/questions/7549694/ggplot2-adding-regression-line-equation-and-r2-on-graph – Matthias Munz Sep 20 '12 at 11:05

2 Answers2

4

use show_guide=TRUE e.g.

 p <- ggplot(df, aes(x, y)) +
geom_point(size=1.2) +
scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
geom_smooth(method="lm", se=FALSE, formula=y~x, colour="blue", fill=NA, size=1.2) +
geom_abline(aes(colour="red"),intercept=0, slope=1, size=1.2,show_guide=TRUE) +
geom_text(aes(x=max(df[,1])/1.4, y=max(df[,2])/1.2, label="lm_eqn(df)"), colour="blue",  parse=TRUE) +
# doesn't work: scale_colour_manual("Lines", labels=c("Main Diagonal", "Regression"), values=c("red", "blue")) +
labs(x="X", y="Y") + opts(legend.position = 'left')

plus you can move legends about using things like+ opts(legend.position = 'left') to get it on the left. I suggest you look at the link provided by Tyler Rinker and also the following:

https://github.com/hadley/ggplot2/wiki/Legend-Attributes

Also no idea what lm_eqn ia so in my code i have surrounded it with "" so it will appear as it is written..

Community
  • 1
  • 1
user1317221_G
  • 15,087
  • 3
  • 52
  • 78
0

I could finally manage to create a legend for the regression and the diagonal line which is located in the bottom right corner and that makes sense:

 p <- ggplot(df, aes(x, y)) +
geom_point(size=1.2) +
scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
geom_abline(aes(colour="red"),intercept=0, slope=1, size=1.2, aes(colour="1"), show_guide=TRUE) + # new code
geom_smooth(method="lm", se=FALSE, formula=y~x, fill=NA, size=1.2, aes(colour="2"), show_guide=TRUE) + # new code
scale_colour_manual("Lines", labels=c("Diagonal", "Regression"), values=c("red", "blue")) +
opts(legend.position = c(0.85, 0.15)) # relative values, must be set individually
Matthias Munz
  • 3,583
  • 4
  • 30
  • 47