Reputation: 49
I have produced a scatter plot in R of expected/observed values. I calculated orthogonal regression and added the line using the following:
library(ggplot2)
library(MethComp)
r<-read_csv("Uni/MSci/Project/DATA/new data sheets/comparisons/for comarison
graphs/R Regression/GCdNi.csv")
x<-r[1]
y<-r[2]
P<-ggplot()+geom_point(aes(x=x,y=y))+
scale_size_area()+xlab("Expected")+ylab("Observed")+ggtitle("G - Cd x Ni")+
xlim(0, 40)+ylim(0, 40)
# Orthogonal, total least squares or Deming regression
deming <- Deming(y=r$Observed, x=r$Expected)[1:2]
deming
R <- prcomp( ~ r$Expected + r$Observed )
slope <- R$rotation[2,1] / R$rotation[1,1]
slope
intercept <- R$center[2] - slope*R$center[1]
intercept
#Plot orthogonal regression
P+geom_abline(intercept = deming[1], slope = deming[2])
This gives me the following plot:
Is there a way I can calculate and add an R squared value to the graph?
Heres some of the data frame to allow for reproduction:
Expected Observed
2.709093153 1.37799781
2.611562579 1.410720257
2.22411805 1.287685907
3.431914392 1.906787706
3.242018129 1.823698676
3.46139841 1.767857729
2.255673738 1.111307235
2.400606765 1.294583377
1.818447253 0.995226256
2.528992184 1.173159775
2.46829393 1.101852756
1.826044939 0.883336715
1.78702201 1.050122993
2.37226253 1.025298403
2.140921846 1.094761918
Upvotes: 0
Views: 1006
Reputation: 362
I could not reproduce your data, but here's how you could do something like that with linear regression.
library(ggplot2)
set.seed(1)
x <- rnorm(20,1,100)
y<- x + rnorm(20,50,10)
regression <- lm(y ~ x)
r2 <- summary(regression)$r.squared
ggplot() + geom_point(aes(x, y)) +
geom_line(aes(x, regression$fitted.values)) +
annotate("text", x = -100, y = 200, label = paste0("r squared = ", r2))
In the future, you should provide a reproducible example.
Upvotes: 3