0

I would like to get single regression line and correlation coefficient instead of multiple regression lines. My code is shown below.

d1 <- structure(list(x1 = c(50.42,62.59,42.53,55.38,65.23,66.17,47.20,29.40,46.22,65.91), y1 = c(7.00,7.50,4.50,7.58,4.00,4.67,3.50,3.00,3.50,4.63)), .Names = c("x1", "y1"), class = "data.frame", row.names = c(NA,-10L)) d2 <- structure(list(x2 = c(33.65,39.16,46.93,35.75,34.50,31.16,44.72,28.63,42.73,40.54,32.14,33.56), y2 = c(3.00,4.00,3.80,2.76,3.54,3.13,3.50,2.92,4.18,4.22,3.23,2.56)), .Names = c("x2", "y2"), class = "data.frame", row.names = c(NA, -12L)) library(reshape2) library(ggplot2) names(d2) <- c("x1", "y2") df <- rbind(melt(d1, id.vars = "x1"), melt(d2, id.vars = "x1")) p1 <-ggplot(df, aes(x1, y = value, colour = variable)) + geom_point(size=4) + theme(axis.text=element_text(size=16), axis.title=element_text(size=18,face="bold"), plot.title=element_text(size=32,face="bold"), legend.text=element_text(size=16), legend.justification=c(0,1),legend.position=c(0,1),legend.title=element_blank() ) + theme(legend.background = element_rect( size=0.5, linetype="solid", colour ="black"), panel.border = element_rect(color="black", size=1, linetype="solid")) + theme(aspect.ratio=1) + labs(x = "x axis", y = "y axis") + xlim(0,100) + ylim(0,10) + geom_smooth(method=lm, se=FALSE, linetype="solid", fullrange=TRUE) + ggtitle("My first plot") + scale_colour_manual(values = c("green","red"), labels = c("d1", "d2")) 

Are there any easy way for doing this?

1 Answer 1

2

In geom_smooth add color="black" (or whatever color you want) outside of aes. This will override the color aesthetic specified in the call to ggplot and result in a single regression line.

geom_smooth(color="black", method="lm", se=FALSE, linetype="solid", fullrange=TRUE) + 

Regarding your comment about annotation: d1 and d2 don't exist in the df data frame. Try this:

annotate(x=20, y=5, label=paste("R = ", round(cor(df$x1, df$value),2)), geom="text", size=4) 
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your answer. Are there any way to print correlation coefficient on the plot. I tried like this : annotate(x=25, y=5, label=paste("R = ", round(cor(df$d1, df$d2),2)), geom="text", size=10.5) . But it doesn't work.
You could just use text(x, ...) to add text to a plot.
text works with base graphics, but ggplot requires either ggplot functions or grid functions.
@eipi10 Thank you so much for your help!
You're right. This older post explains how to add text to ggplot: stackoverflow.com/questions/28755576/add-text-to-ggplot

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.