I have loaded 4 databases into R, each of them have 2 columns: "Rating" and "Temperature". I want to create a graph with 4 regression lines (without data points inside the plot) of Ratings and Temperature. My code is:
y1<-Database1$`Rating1'
y2<-Database2$'Rating2'
y3<-Database3$`Rating3`
y4<-Database4$`Rating4`
x1<-Database1$`Mean Temperature (°C)`
x2<-Database2$`Mean Temperature (°C)`
x3<-Database3$`Mean Temperature (°C)`
x4<-Database4$`Mean Temperature (°C)`
reg1 <- lm(y1 ~ x1, data=Database1)
reg2 <- lm(y2 ~ x2, data=Database2)
reg3 <- lm(y3 ~ x3, data=Database3)
reg4 <- lm(y4 ~ x4, data=Database4)
equation1=function(x){coef(reg1)[2]*x+coef(reg1)[1]}
equation2=function(x){coef(reg2)[2]*x+coef(reg2)[1]}
equation3=function(x){coef(reg3)[2]*x+coef(reg3)[1]}
equation4=function(x){coef(reg4)[2]*x+coef(reg4)[1]}
library(ggplot2)
ggplot(Database1,aes(`Mean Temperature (°C)`,`Rating1`))+
ggtitle("Sub-ratings vs Temperature (°C)") +
xlab("Temperature (°C)") + ylab("Sub-ratings")+
stat_function(fun=equation1,geom="line",color="skyblue",size=1)+
stat_function(fun=equation2,geom="line",color="orangered",size=1)+
stat_function(fun=equation3,geom="line",color="turquoise",size=1)+
stat_function(fun=equation4,geom="line",color="royalblue",size=1)+
theme(
plot.title = element_text(size=12,hjust = 0.5),
axis.title.x = element_text(size=11),
axis.title.y = element_text(size=11)
)+ylim(2,5)
I have created a graph like this.
I hope to add a legend for 4 lines to explain which color is for which Rating. Would be better to place the legend outside.
Thank you!