[R] calculating area between plot lines

Hans W Borchers hwborchers at googlemail.com
Tue Sep 7 13:40:01 CEST 2010

A. Marcia BARBOSA <anamarciabarbosa <at> gmail.com> writes:
>
> Hi everyone. I have these data:
>
> probClass<-seq(0,0.9,0.1)
> prob1<-c(0.0070,0.0911,0.1973,0.2949,0.3936,0.5030,0.5985,0.6869,0.7820,0.8822)
> prob2<-c(0.0066,0.0791,0.2358,0.3478,0.3714,0.3860,0.6667,0.6400,0.7000,1.0000)
>
> # which I'm plotting as follows:
>
> plot(probClass,prob1,xlim=c(0,1),ylim=c(0,1),xaxs='i',yaxs='i',type="n")
> lines(probClass,prob1)
> lines(probClass,prob2)
> polygon(c(probClass,rev(probClass)),c(prob2,rev(prob1)),col="red",border=NA)
>
> Given that the total area of the plot is 1, how can I calculate the
> area between the plotted lines (red polygon)? I have only found the
> areapl function in the splancs package, but it doesn't work for
> self-intersecting polygons..
>
> Any help will be gratefully received. Cheers,
> Márcia
>

Remember that the area between two curves is the same as the integral of the
difference between these two curves (resp. its absolute values); thus it is
easy to compute the area directly:

----
f1 <- approxfun(probClass, prob1-prob2)     # piecewise linear function
f2 <- function(x) abs(f1(x))                 # take the positive value

integrate(f2, 0, 0.9)
0.03548023 with absolute error < 1.6e-06
----

where the true value is 0.03547927 (using the triangle/trapez area formula).

Hans Werner