【问题标题】:Plot the area under the curve (integral) of a set of x and y values in R绘制 R 中一组 x 和 y 值的曲线下面积(积分)
【发布时间】:2017-10-21 00:14:20
【问题描述】:

我有一组数据点,我想为其绘制“积分”。

例如:

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 以下的区域,另一方面它不是关于显示阴影区域,而是关于构造一个积分函数......

【问题讨论】:

  • @MaciejPitucha re:一个可重复的答案,你的愿望就是我的命令。然而,绝对不是那个问题的重复。
  • 我的意思是可复制的例子,对不起。
  • 是的,我刚刚添加了一个。
  • 而且显然不是重复的,我误解了你的问题。
  • 好吧,我第一次可能会更清楚。

标签: r integral


【解决方案1】:

我相信您想实现这一目标:

请注意,红线和蓝线不相同 - 这取决于您计算面积的点数。如果在第一行代码中增加数字 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)

【讨论】:

  • 谢谢,这很好。我最终确实使用了 smooth.spline
【解决方案2】:

@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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-13
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2016-11-24
    相关资源
    最近更新 更多