问题描述
我正在尝试计算通过一系列x-y坐标的类似于Bezier的样条曲线.一个示例类似于Matlab中cscvn
函数的以下输出(示例链接):
I'm trying to calculate a Bezier-like spline curve that passes through a sequence of x-y coordinates. An example would be like the following output from the cscvn
function in Matlab (example link):
我相信(不再维护)grid
软件包用于执行此操作(grid.xspline
功能?),但是我无法安装该软件包的存档版本,也找不到任何示例完全符合我的意愿.
I believe the (no longer maintained) grid
package used to do this (grid.xspline
function?), but I haven't been able to install an archived version of the package, and don't find any examples exactly along the lines of what I would like.
bezier
程序包看起来也很有前途,但是它非常慢,我也无法完全正确:
The bezier
package also looks promising, but it is very slow and I also can't get it quite right:
library(bezier)
set.seed(1)
n <- 10
x <- runif(n)
y <- runif(n)
p <- cbind(x,y)
xlim <- c(min(x) - 0.1*diff(range(x)), c(max(x) + 0.1*diff(range(x))))
ylim <- c(min(y) - 0.1*diff(range(y)), c(max(y) + 0.1*diff(range(y))))
plot(p, xlim=xlim, ylim=ylim)
text(p, labels=seq(n), pos=3)
bp <- pointsOnBezier(cbind(x,y), n=100)
lines(bp$points)
arrows(bp$points[nrow(bp$points)-1,1], bp$points[nrow(bp$points)-1,2],
bp$points[nrow(bp$points),1], bp$points[nrow(bp$points),2]
)
如您所见,除最终值外,它不经过任何点.
As you can see, it doesn't pass through any points except the end values.
非常感谢您在这里提供一些指导!
I would greatly appreciate some guidance here!
推荐答案
这可能不是最好的方法,grid
位当然不是无效的.它是R安装中的默认软件包.它是用于绘制诸如点阵图和ggplot之类的库的基础图形引擎.您不需要安装它,只需加载它即可.这就是我可能会翻译您的代码以使用grid.xpline
It may not the be the best approach, bit grid
certainly isn't inactive. It's included as a default package with the R installation. It's the underlying graphics engine for plotting libraries like lattice and ggplot. You shouldn't need to install it, you should just be able to load it. Here's how I might translate your code to use grid.xpline
set.seed(1)
n <- 10
x <- runif(n)
y <- runif(n)
xlim <- c(min(x) - 0.1*diff(range(x)), c(max(x) + 0.1*diff(range(x))))
ylim <- c(min(y) - 0.1*diff(range(y)), c(max(y) + 0.1*diff(range(y))))
library(grid)
grid.newpage()
pushViewport(viewport(xscale=xlim, yscale=ylim))
grid.points(x, y, pch=16, size=unit(2, "mm"),
default.units="native")
grid.text(seq(n), x,y, just=c("center","bottom"),
default.units="native")
grid.xspline(x, y, shape=c(0,rep(-1, 10-2),0), open=TRUE,
default.units="native")
popViewport()
结果
请注意,网格是非常底层的,因此使用起来并非易事,但确实可以让您更好地控制绘制的内容和位置.
note that grid is pretty low-level so it's not super easy to work with, but it does allow you far more control of what and where you plot.
如果您想沿曲线提取点而不是绘制它,请查看?xsplinePoints
帮助页面.
And if you want to extract the points along the curve rather than draw it, look at the ?xsplinePoints
help page.
这篇关于计算R中的2D样条曲线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!