2017-10-18 72 views
0

我有一組數據點,我想繪製「積分」。在R中繪製一組x和y值的曲線(積分)的面積

例如:

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

如何繪製從0積分到x在區間,也就是說,010?積分是由曲線和y=0限定的區域。

這當然應該看起來非常像1 - cos(x)的情節,但讓我們假設我們不知道y = f(x)實際上是什麼。

我知道該怎麼做的唯一的事情似乎很有道理的:

spl = smooth.spline(x, y) 

但是我不知道下一步該怎麼做。

編輯:這不是曲線下陰影的重複,對於一件事,y = 0以下的區域需要被減去,另一個不是顯示陰影區域,而是關於構建一個積分函數。 。

+0

@MaciejPitucha重:可重複的答案,你的願望就是我的命令。但絕對不是該問題的重複。 –

+0

我的意思是可複製的例子,對不起。 –

+0

是的,我剛剛加了一個。 –

回答

0

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

enter image description here

1

我相信你想實現的是:

enter image description here

請注意,紅線和藍線是不相同的 - 這取決於你計算面積的點數。如果在第一行代碼中增加數字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) 
+0

謝謝,這很好。我最終使用smooth.spline找出了它 –