简体   繁体   English

如何估计 R 中沿图形线的点的坐标?

[英]How do I estimate the coordinates of points along a graphed line in R?

Assume I have data:假设我有数据:

x <- c(1900,1930,1944,1950,1970,1980,1983,1984)
y <- c(100,300,500,1500,2500,3500,4330,6703)

I then plot this data and add a line graph between my known x and y coordinates:然后我 plot 这个数据并在我已知的 x 和 y 坐标之间添加一个折线图:

plot(x,y)
lines(x,y)

Is there a way to predict coordinates of unknown points along the graphed line?有没有办法预测沿图形线的未知点的坐标?

You can use approxfun . 您可以使用approxfun

f <- approxfun(x, y=y)

f(seq(1900, 2000, length.out = 10))
# [1]  100.0000  174.0741  248.1481  347.6190  574.0741 1777.7778 2333.3333
# [8] 3277.7778        NA        NA

Note the NA, when the sequence is outside the range of interpolated points (there are left and right options to approxfun). 请注意,当序列不在插值点的范围内时,NA(近似值有左右选项)。

You can manually calculate the slopes of each line. 您可以手动计算每条线的斜率。

The equation of a line is given by 一条线的方程由

y − y1 = grad*(x − x1)

where grad is calculated by the change in y divided by the change in x 其中grad由y的变化除以x的变化来计算

We can produce equations for each line by using two points from each line in the plot. 通过使用图中每条线的两个点,我们可以为每条线生成方程式。

f2 <- function(xnew, X=x, Y=y) {
             id0 <- findInterval(xnew, X, rightmost=T)
             id1 <- id0 + 1
             grad <- (Y[id1] - Y[id0]) / (X[id1] - X[id0]) 
             Y[id0] + grad* (xnew - X[id0])
 }

 f2(x)
#[1]  100  300  500 1500 2500 3500 4330 6703

f <- approxfun(x, y=y) # bunks
f(seq(1900, 2000, length.out = 10))
# [1]  100.0000  174.0741  248.1481  347.6190  574.0741 1777.7778 2333.3333 3277.7778        NA        NA
f2(seq(1900, 2000, length.out = 10))
# [1]  100.0000  174.0741  248.1481  347.6190  574.0741 1777.7778 2333.3333 3277.7778        NA        NA

If you wanted to extrapolate using the final slope, you can do this by adding the all.in=TRUE argument to findInterval . 如果要使用最终斜率进行推断,则可以通过将all.in=TRUE参数添加到findInterval

With that said, approxfun does it better & easier! approxfun如此, approxfun更好,更轻松!

Or, if you want to approximate points along the lines in regular intervals, you can use approx instead of approxfun .或者,如果您想要以规则的间隔沿线近似点,您可以使用approx而不是approxfun For that purpose, this maybe saves you a tiny bit of coding.为此,这可能会为您节省一些编码。

x <- c(1900,1930,1944,1950,1970,1980,1983,1984)
y <- c(100,300,500,1500,2500,3500,4330,6703)

new_points <- approx(x, y)
lapply(new_points, head)
#> $x
#> [1] 1900.000 1901.714 1903.429 1905.143 1906.857 1908.571
#> 
#> $y
#> [1] 100.0000 111.4286 122.8571 134.2857 145.7143 157.1429
plot(new_points)
lines(x,y)

Created on 2022-11-20 with reprex v2.0.2创建于 2022-11-20,使用reprex v2.0.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM