gpt4 book ai didi

r - 在 R 中从一条线偏移绘制一条平行线

转载 作者:行者123 更新时间:2023-12-02 04:53:13 25 4
gpt4 key购买 nike

我有代表沿着一些街道行驶的线串。但我实际上想代表骑自行车者的旅程,它偏离线路,即他们在路边附近行驶。我正在努力思考如何去做。我制作了一段可重现的 R 代码来进行说明。

## Let's say I have a route along some streets.
library(ggplot2)

## It can be described by this
data <- data.frame(x = c(1,3,10,5,0,5),
y = c(1,3,1,0,5,7),
label = c('a', 'b', 'c', 'd', 'e', 'f'))
## Visualised by this
ggplot(data, aes(x, y)) +
geom_path() +
geom_text(aes(label=label),hjust=0, vjust=0)

enter image description here

但是我想做的就是模拟有人在骑自行车。假设它们距离道路中心线 0.5 公里,向左行驶,但当然“左”是相对于路线的方向 旅程的开始实际上看起来像这样 请注意“new_x”和“new_y” ' 在数学上是不正确的。它们是出于说明目的的估计。

data          <- data.frame(x = c(1,3,10,5,0,5),
y = c(1,3,1,0,5,7),
new_x = c(0.7, 3, 10.5,NA, NA, NA) ,
new_y = c(1.5, 3.5, 1, NA, NA, NA),
label = c('a', 'b', 'c', 'd', 'e', 'f'))

## Visualised by this showing the old line and the new line
ggplot(data, aes(x, y)) +
geom_path() +
geom_text(aes(label=label),hjust=0, vjust=0) +
geom_path(data = data, aes(new_x, new_y), colour='red')

enter image description here

所以问题是如何正确计算 new_x 和 new_y 以创建一条连续线,表示骑自行车者的旅程与道路中心的偏移

最佳答案

有一个包提供样条曲线的偏移计算: https://www.stat.auckland.ac.nz/~paul/Reports/VWline/offset-xspline/offset-xspline.html

这是一些非常基本的近似值。我故意将拐角处留了下来,因为这可能是自行车转弯方式的更好近似。另请注意,如果您需要计算“向内”偏移,则需要一些额外的步骤:

x <-  c(1,3,10,5,0,5)
y <- c(1,3,1,0,5,7)
d <- 0.5 # distance away from the road


# Given a vector (defined by 2 points) and the distance,
# calculate a new vector that is distance away from the original
segment.shift <- function(x, y, d){

# calculate vector
v <- c(x[2] - x[1],y[2] - y[1])

# normalize vector
v <- v/sqrt((v[1]**2 + v[2]**2))

# perpendicular unit vector
vnp <- c( -v[2], v[1] )

return(list(x = c( x[1] + d*vnp[1], x[2] + d*vnp[1]),
y = c( y[1] + d*vnp[2], y[2] + d*vnp[2])))

}

plot(x,y, xlim=c(-1,11), ylim=c(-1,11), type="l", main= "Bicycle path" )

# allocate memory for the bike path
xn <- numeric( (length(x) - 1) * 2 )
yn <- numeric( (length(y) - 1) * 2 )

for ( i in 1:(length(x) - 1) ) {
xs <- c(x[i], x[i+1])
ys <- c(y[i], y[i+1])
new.s <- segment.shift( xs, ys, d )
xn[(i-1)*2+1] <- new.s$x[1] ; xn[(i-1)*2+2] <- new.s$x[2]
yn[(i-1)*2+1] <- new.s$y[1] ; yn[(i-1)*2+2] <- new.s$y[2]
}

# draw the path
lines(xn, yn, col="brown", lwd =2, lty=2)

enter image description here

关于r - 在 R 中从一条线偏移绘制一条平行线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50275195/

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