将R平方值添加到R中的正交回归线

时间:2018-03-21 13:50:22

标签: r ggplot2 regression

我在R中产生了预期/观测值的散点图。我计算了正交回归并使用以下内容添加了该行:

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])

这给了我以下情节:Scatter plot

有没有办法可以计算并在图表中添加R平方值?

以下是允许复制的一些数据框架:

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

1 个答案:

答案 0 :(得分:2)

我无法重现您的数据,但是您可以通过线性回归来执行此类操作。

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))

将来,您应该提供a reproducible example