gpt4 book ai didi

r - 在ggplot中添加正交回归线

转载 作者:行者123 更新时间:2023-12-03 09:02:16 28 4
gpt4 key购买 nike

我使用以下脚本在 R 中绘制了散点图,将预期值与观察值进行比较:

library(ggplot2)
library(dplyr)


r<-read_csv("Uni/MSci/Project/DATA/new data sheets/comparisons/for comarison
graphs/R Regression/GAcAs.csv")
x<-r[1]
y<-r[2]

ggplot()+geom_point(aes(x=x,y=y))+
scale_size_area() +
xlab("Expected") +
ylab("Observed") +
ggtitle("G - As x Ac")+ xlim(0, 40)+ylim(0, 40)

我的情节如下:

enter image description here

然后我想添加一条正交回归线(因为预期值和观察值都可能存在错误)。我使用以下公式计算了 beta 值:

v <- prcomp(cbind(x,y))$rotation
beta <- v[2,1]/v[1,1]

有没有办法在我的图中添加正交回归线?

最佳答案

借用这个blog post &这个answer 。基本上,您需要 MethComp 中的 Deming 函数或 stats 包中的 prcomp 以及自定义函数 perp.segment.coord。以下是取自上述博客文章的示例。

library(ggplot2)
library(MethComp)

data(airquality)
airquality <- na.exclude(airquality)

# Orthogonal, total least squares or Deming regression
deming <- Deming(y=airquality$Wind, x=airquality$Temp)[1:2]
deming
#> Intercept Slope
#> 24.8083259 -0.1906826

# Check with prcomp {stats}
r <- prcomp( ~ airquality$Temp + airquality$Wind )
slope <- r$rotation[2,1] / r$rotation[1,1]
slope
#> [1] -0.1906826

intercept <- r$center[2] - slope*r$center[1]
intercept
#> airquality$Wind
#> 24.80833

# https://stackoverflow.com/a/30399576/786542
perp.segment.coord <- function(x0, y0, ortho){
# finds endpoint for a perpendicular segment from the point (x0,y0) to the line
# defined by ortho as y = a + b*x
a <- ortho[1] # intercept
b <- ortho[2] # slope
x1 <- (x0 + b*y0 - a*b)/(1 + b^2)
y1 <- a + b*x1
list(x0=x0, y0=y0, x1=x1, y1=y1)
}

perp.segment <- perp.segment.coord(airquality$Temp, airquality$Wind, deming)
perp.segment <- as.data.frame(perp.segment)

# plot
plot.y <- ggplot(data = airquality, aes(x = Temp, y = Wind)) +
geom_point() +
geom_abline(intercept = deming[1],
slope = deming[2]) +
geom_segment(data = perp.segment,
aes(x = x0, y = y0, xend = x1, yend = y1),
colour = "blue") +
theme_bw()

enter image description here

reprex package 创建于 2018-03-19 (v0.2.0)。

关于r - 在ggplot中添加正交回归线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49368754/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com