绘制 R 中一组 x 和 y 值的曲线(积分)下的面积

Plot the area under the curve (integral) of a set of x and y values in R

我有一组数据点,我想为其绘制 "integral"。

例如:

x = seq(from=0, to=9, by=0.05)
y = sin(x)

如何在区间内绘制从 0x 的积分,比如说 010?其中积分是由曲线和 y=0 包围的面积。

这当然看起来很像 1 - cos(x) 的情节,但假设我们不知道 y = f(x) 到底是什么。

我唯一知道该怎么做似乎有意义的是:

spl = smooth.spline(x, y)

但是我不知道下一步该做什么。

编辑:这不是曲线下阴影的副本,一方面需要减去 y=0 以下的区域,另一方面它不是关于显示阴影区域,而是关于构造一个积分函数。 ..

我相信你想实现:

请注意,红线和蓝线并不相同 - 这取决于您计算面积的点数。如果您在第一行代码中增加数字 500,绘图上的线条会更近。 代码:

x <- seq(from=0, to=10, length.out = 500)
n <- rep(1, length(x))
y <- sin(x)

plot(x,y, type="l")
lines(x, 1-cos(x), col="red")
lines(x, cumsum(y*x/cumsum(n)), col="blue")
legend(x="bottomright", 
       col=c("black","red", "blue"), 
       legend=c("sin", "1-cos", "integral"),
       lty=1)

@Maciej Pitucha 的回答也很好,但我最终搞砸了我最初尝试用 smooth.spline() 做的事情,它似乎更适合我的实际数据。

test.x = seq(from=0, to=9, by=0.05)
test.y = sin(x)
spl = smooth.spline(y=test.y, x=test.x)
f = function(x) {predict(spl, x)$y}
f.int = function(x) {integrate(f, lower=0, upper=x)$value}
f.int.vec = Vectorize(f.int, vectorize.args='x')

plot(test.x, test.y, type="l", ylim = c(-1,2))
lines(test.x, 1-cos(test.x), col="red")
lines(test.x, f.int.vec(test.x), col="blue")
legend(x="bottomright", 
       col=c("black","red", "blue"), 
       legend=c("sin", "1-cos", "integral"),
       lty=1)