Area between the two curvesHow to make a great R reproducible exampleFill region between two loess-smoothed lines in R with ggplotHow to measure area between 2 distribution curves in R / ggplot2Calculate Area Between 2 CurvesCalculating the area between a curve and a straight line without finding the functionError calculating the area between two lines using “integrate”Shading a kernel density plot between two points.Shade (fill or color) area under density curve by quantileShading (faceted) density plots between two points ggplot2Error calculating the area between two lines using “integrate”Compute area under density estimation curve, i.e., probabilityHow to plot the difference between two ggplot density distributions?Calculating area between two plots in RHow to find positive area only between two curves in RPlotting the area under the curve of various distributions in RHow to measure area between 2 distribution curves in R after certain X range?

Sum of Parts of An Array - JavaScript

Getting geometries of hurricane's 'cone of uncertainty' using shapely?

Where can I get macOS Catalina Beta version?

Did Wakanda officially get the stuff out of Bucky's head?

Why are there so many religions and gods?

What are good ways to spray paint a QR code on a footpath?

What does Mildred mean by this line in Three Billboards Outside Ebbing, Missouri?

Should I report a leak of confidential HR information?

I'm reinstalling my Linux desktop, how do I keep SSH logins working?

Way to find when system health file is rolling over

How can my story take place on Earth without referring to our existing cities and countries?

How can I reduce the sound of rain on a range hood vent?

I hit a pipe with a mower and now it won't turn

Miss Toad and her frogs

What could a reptilian race tell by candling their eggs?

Should I share with a new service provider a bill from its competitor?

Is it allowed to spend a night in the first entry country before moving to the main destination?

Details of video memory access arbitration in Space Invaders

Different budgets within roommate group

Wrong corporate name on employment agreement

Why does a brace command group need spaces after the opening brace in POSIX Shell Grammar?

What does grep -v "grep" mean and do?

Averting Real Women Don’t Wear Dresses

Can 'leave' mean 'forget'?



Area between the two curves


How to make a great R reproducible exampleFill region between two loess-smoothed lines in R with ggplotHow to measure area between 2 distribution curves in R / ggplot2Calculate Area Between 2 CurvesCalculating the area between a curve and a straight line without finding the functionError calculating the area between two lines using “integrate”Shading a kernel density plot between two points.Shade (fill or color) area under density curve by quantileShading (faceted) density plots between two points ggplot2Error calculating the area between two lines using “integrate”Compute area under density estimation curve, i.e., probabilityHow to plot the difference between two ggplot density distributions?Calculating area between two plots in RHow to find positive area only between two curves in RPlotting the area under the curve of various distributions in RHow to measure area between 2 distribution curves in R after certain X range?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I have two sets of data



I had plotted two probability density functions. Now I want the area between the two probability density functions, which are in certain x range.



I tried to integrate the area, trapezoidal rule etc:



Calculating the area between a curve and a straight line without finding the function



Error calculating the area between two lines using "integrate"



How to measure area between 2 distribution curves in R / ggplot2



but all are in vain.



Here is the link to the data i am working on.



https://sheet.zoho.com/sheet/editor.do?doc=1ff030ea1af35f06f8303927d7ea62b3c4b04bdae021555e8cc43ed0569cb2aaceb26368f93db4d15ac66cf7662d9a7873e889e1763139a49ffd68e7843e0b44



dens.pre=density(TX/10)
dens.post=density(TX30/10)`
plot(dens.pre,col="green")
lines(dens.post,col="red")

locator()
#$x
#[1] 18.36246

#$y
#[1] 0.05632428

abline(v=18.3,col="red")


Finding the area between the two curves for X > 18.3.



Area between the curves:
enter image description here










share|improve this question
























  • Perhaps area.between.curves() in the geiger package could be of some assistance?

    – tomasu
    Mar 25 at 12:50











  • Hi, thanks for the reply @ThomasJohnFlaherty I tried it, but its not working in R version 3.0.0+, it's for lower version of R. I installed the package and it seems not to load. this is what i get lines(dens.post,col="red") > area.between.curves(x, dens.pre, dens.post, xrange = c(18.3,35)) Error: could not find function "area.between.curves"

    – chanakya chan
    Mar 25 at 13:04












  • Possible duplicate of Calculate Area Between 2 Curves

    – Cettt
    Mar 25 at 13:04






  • 1





    chanakya chan, did you try the package? It depends on R at least 2.15, but since it was last updated to CRAN two months ago, I find it hard to believe that it was accepted if it does not support R-3. And I cannot find where in its source it does anything version-specific.

    – r2evans
    Mar 25 at 13:17







  • 2





    Just because you get an unexpected result does not mean the package is broken or does not support up-to-date versions of R. We cannot help you, unfortunately, since we don't have any sample data. (It really helps to have a fully-reproducible question, including sample data generated programmatically or provided with dput. For good-question references, please see stackoverflow.com/questions/5963269, stackoverflow.com/help/mcve, and stackoverflow.com/tags/r/info.)

    – r2evans
    Mar 25 at 13:38

















1















I have two sets of data



I had plotted two probability density functions. Now I want the area between the two probability density functions, which are in certain x range.



I tried to integrate the area, trapezoidal rule etc:



Calculating the area between a curve and a straight line without finding the function



Error calculating the area between two lines using "integrate"



How to measure area between 2 distribution curves in R / ggplot2



but all are in vain.



Here is the link to the data i am working on.



https://sheet.zoho.com/sheet/editor.do?doc=1ff030ea1af35f06f8303927d7ea62b3c4b04bdae021555e8cc43ed0569cb2aaceb26368f93db4d15ac66cf7662d9a7873e889e1763139a49ffd68e7843e0b44



dens.pre=density(TX/10)
dens.post=density(TX30/10)`
plot(dens.pre,col="green")
lines(dens.post,col="red")

locator()
#$x
#[1] 18.36246

#$y
#[1] 0.05632428

abline(v=18.3,col="red")


Finding the area between the two curves for X > 18.3.



Area between the curves:
enter image description here










share|improve this question
























  • Perhaps area.between.curves() in the geiger package could be of some assistance?

    – tomasu
    Mar 25 at 12:50











  • Hi, thanks for the reply @ThomasJohnFlaherty I tried it, but its not working in R version 3.0.0+, it's for lower version of R. I installed the package and it seems not to load. this is what i get lines(dens.post,col="red") > area.between.curves(x, dens.pre, dens.post, xrange = c(18.3,35)) Error: could not find function "area.between.curves"

    – chanakya chan
    Mar 25 at 13:04












  • Possible duplicate of Calculate Area Between 2 Curves

    – Cettt
    Mar 25 at 13:04






  • 1





    chanakya chan, did you try the package? It depends on R at least 2.15, but since it was last updated to CRAN two months ago, I find it hard to believe that it was accepted if it does not support R-3. And I cannot find where in its source it does anything version-specific.

    – r2evans
    Mar 25 at 13:17







  • 2





    Just because you get an unexpected result does not mean the package is broken or does not support up-to-date versions of R. We cannot help you, unfortunately, since we don't have any sample data. (It really helps to have a fully-reproducible question, including sample data generated programmatically or provided with dput. For good-question references, please see stackoverflow.com/questions/5963269, stackoverflow.com/help/mcve, and stackoverflow.com/tags/r/info.)

    – r2evans
    Mar 25 at 13:38













1












1








1


0






I have two sets of data



I had plotted two probability density functions. Now I want the area between the two probability density functions, which are in certain x range.



I tried to integrate the area, trapezoidal rule etc:



Calculating the area between a curve and a straight line without finding the function



Error calculating the area between two lines using "integrate"



How to measure area between 2 distribution curves in R / ggplot2



but all are in vain.



Here is the link to the data i am working on.



https://sheet.zoho.com/sheet/editor.do?doc=1ff030ea1af35f06f8303927d7ea62b3c4b04bdae021555e8cc43ed0569cb2aaceb26368f93db4d15ac66cf7662d9a7873e889e1763139a49ffd68e7843e0b44



dens.pre=density(TX/10)
dens.post=density(TX30/10)`
plot(dens.pre,col="green")
lines(dens.post,col="red")

locator()
#$x
#[1] 18.36246

#$y
#[1] 0.05632428

abline(v=18.3,col="red")


Finding the area between the two curves for X > 18.3.



Area between the curves:
enter image description here










share|improve this question
















I have two sets of data



I had plotted two probability density functions. Now I want the area between the two probability density functions, which are in certain x range.



I tried to integrate the area, trapezoidal rule etc:



Calculating the area between a curve and a straight line without finding the function



Error calculating the area between two lines using "integrate"



How to measure area between 2 distribution curves in R / ggplot2



but all are in vain.



Here is the link to the data i am working on.



https://sheet.zoho.com/sheet/editor.do?doc=1ff030ea1af35f06f8303927d7ea62b3c4b04bdae021555e8cc43ed0569cb2aaceb26368f93db4d15ac66cf7662d9a7873e889e1763139a49ffd68e7843e0b44



dens.pre=density(TX/10)
dens.post=density(TX30/10)`
plot(dens.pre,col="green")
lines(dens.post,col="red")

locator()
#$x
#[1] 18.36246

#$y
#[1] 0.05632428

abline(v=18.3,col="red")


Finding the area between the two curves for X > 18.3.



Area between the curves:
enter image description here







r






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 25 at 13:49







chanakya chan

















asked Mar 25 at 12:35









chanakya chanchanakya chan

83 bronze badges




83 bronze badges












  • Perhaps area.between.curves() in the geiger package could be of some assistance?

    – tomasu
    Mar 25 at 12:50











  • Hi, thanks for the reply @ThomasJohnFlaherty I tried it, but its not working in R version 3.0.0+, it's for lower version of R. I installed the package and it seems not to load. this is what i get lines(dens.post,col="red") > area.between.curves(x, dens.pre, dens.post, xrange = c(18.3,35)) Error: could not find function "area.between.curves"

    – chanakya chan
    Mar 25 at 13:04












  • Possible duplicate of Calculate Area Between 2 Curves

    – Cettt
    Mar 25 at 13:04






  • 1





    chanakya chan, did you try the package? It depends on R at least 2.15, but since it was last updated to CRAN two months ago, I find it hard to believe that it was accepted if it does not support R-3. And I cannot find where in its source it does anything version-specific.

    – r2evans
    Mar 25 at 13:17







  • 2





    Just because you get an unexpected result does not mean the package is broken or does not support up-to-date versions of R. We cannot help you, unfortunately, since we don't have any sample data. (It really helps to have a fully-reproducible question, including sample data generated programmatically or provided with dput. For good-question references, please see stackoverflow.com/questions/5963269, stackoverflow.com/help/mcve, and stackoverflow.com/tags/r/info.)

    – r2evans
    Mar 25 at 13:38

















  • Perhaps area.between.curves() in the geiger package could be of some assistance?

    – tomasu
    Mar 25 at 12:50











  • Hi, thanks for the reply @ThomasJohnFlaherty I tried it, but its not working in R version 3.0.0+, it's for lower version of R. I installed the package and it seems not to load. this is what i get lines(dens.post,col="red") > area.between.curves(x, dens.pre, dens.post, xrange = c(18.3,35)) Error: could not find function "area.between.curves"

    – chanakya chan
    Mar 25 at 13:04












  • Possible duplicate of Calculate Area Between 2 Curves

    – Cettt
    Mar 25 at 13:04






  • 1





    chanakya chan, did you try the package? It depends on R at least 2.15, but since it was last updated to CRAN two months ago, I find it hard to believe that it was accepted if it does not support R-3. And I cannot find where in its source it does anything version-specific.

    – r2evans
    Mar 25 at 13:17







  • 2





    Just because you get an unexpected result does not mean the package is broken or does not support up-to-date versions of R. We cannot help you, unfortunately, since we don't have any sample data. (It really helps to have a fully-reproducible question, including sample data generated programmatically or provided with dput. For good-question references, please see stackoverflow.com/questions/5963269, stackoverflow.com/help/mcve, and stackoverflow.com/tags/r/info.)

    – r2evans
    Mar 25 at 13:38
















Perhaps area.between.curves() in the geiger package could be of some assistance?

– tomasu
Mar 25 at 12:50





Perhaps area.between.curves() in the geiger package could be of some assistance?

– tomasu
Mar 25 at 12:50













Hi, thanks for the reply @ThomasJohnFlaherty I tried it, but its not working in R version 3.0.0+, it's for lower version of R. I installed the package and it seems not to load. this is what i get lines(dens.post,col="red") > area.between.curves(x, dens.pre, dens.post, xrange = c(18.3,35)) Error: could not find function "area.between.curves"

– chanakya chan
Mar 25 at 13:04






Hi, thanks for the reply @ThomasJohnFlaherty I tried it, but its not working in R version 3.0.0+, it's for lower version of R. I installed the package and it seems not to load. this is what i get lines(dens.post,col="red") > area.between.curves(x, dens.pre, dens.post, xrange = c(18.3,35)) Error: could not find function "area.between.curves"

– chanakya chan
Mar 25 at 13:04














Possible duplicate of Calculate Area Between 2 Curves

– Cettt
Mar 25 at 13:04





Possible duplicate of Calculate Area Between 2 Curves

– Cettt
Mar 25 at 13:04




1




1





chanakya chan, did you try the package? It depends on R at least 2.15, but since it was last updated to CRAN two months ago, I find it hard to believe that it was accepted if it does not support R-3. And I cannot find where in its source it does anything version-specific.

– r2evans
Mar 25 at 13:17






chanakya chan, did you try the package? It depends on R at least 2.15, but since it was last updated to CRAN two months ago, I find it hard to believe that it was accepted if it does not support R-3. And I cannot find where in its source it does anything version-specific.

– r2evans
Mar 25 at 13:17





2




2





Just because you get an unexpected result does not mean the package is broken or does not support up-to-date versions of R. We cannot help you, unfortunately, since we don't have any sample data. (It really helps to have a fully-reproducible question, including sample data generated programmatically or provided with dput. For good-question references, please see stackoverflow.com/questions/5963269, stackoverflow.com/help/mcve, and stackoverflow.com/tags/r/info.)

– r2evans
Mar 25 at 13:38





Just because you get an unexpected result does not mean the package is broken or does not support up-to-date versions of R. We cannot help you, unfortunately, since we don't have any sample data. (It really helps to have a fully-reproducible question, including sample data generated programmatically or provided with dput. For good-question references, please see stackoverflow.com/questions/5963269, stackoverflow.com/help/mcve, and stackoverflow.com/tags/r/info.)

– r2evans
Mar 25 at 13:38












1 Answer
1






active

oldest

votes


















0














With trapezoidal rule you could probably calculate it like this:



d0 <- dens.pre
d1 <- dens.post
f0 <- approxfun(d0$x, d0$y)
f1 <- approxfun(d1$x, d1$y)

# defining x range of the density overlap
ovrng <- c(18.3, min(max(d0$x), max(d1$x)))

# dividing it to sections (for example n=500)
i <- seq(min(ovrng), max(ovrng), length.out=500)

# calculating the distance between the density curves
h1 <- f0(i)-f1(i)
h2 <- f1(i)-f0(i)

#and using the formula for the area of a trapezoid we add up the areas
area1<-sum( (h1[-1]+h1[-length(h1)]) /2 *diff(i) *(h1[-1]>=0+0)) # for the regions where d1>d0
area2<-sum( (h2[-1]+h2[-length(h2)]) /2 *diff(i) *(h2[-1]>=0+0)) # for the regions where d1<d0
area_total <- area1 + area2
area_total


Though, since you are interested only in the area where one curve remain below the other for the whole range, this can be shortened:



d0 <- dens.pre
d1 <- dens.post
f0 <- approxfun(d0$x, d0$y)
f1 <- approxfun(d1$x, d1$y)

# defining x range of the density overlap
ovrng <- c(18.3, min(max(d0$x), max(d1$x)))

# dividing it to sections (for example n=500)
i <- seq(min(ovrng), max(ovrng), length.out=500)

# calculating the distance between the density curves
h1 <- f1(i)-f0(i)

#and using the formula for the area of a trapezoid we add up the areas where d1>d0
area<-sum( (h1[-1]+h1[-length(h1)]) /2 *diff(i) *(h1[-1]>=0+0))
area

#We can plot the region using
plot(d0, main="d0=black, d1=green")
lines(d1, col="green")
jj<-which(h>0 & seq_along(h) %% 5==0); j<-i[jj];
segments(j, f1(j), j, f1(j)-h[jj])


There are other (and more detailed) solutions here and here






share|improve this answer

























  • Hi, I tried the same procedure yesterday. I got the total area between the curves. But I need area between curves after an X value 18.3, which is the area between the curves after the redline as shown in the above fig.

    – chanakya chan
    Mar 25 at 14:05











  • Hi, Thank you for the comment. I corrected the code so it will calculate after 18.3.

    – Oka
    Mar 25 at 14:33











  • Thank you very much@-Oka

    – chanakya chan
    Mar 25 at 14:35











  • @chanakya chan : Is it acceptable / sufficient solution?

    – Oka
    Mar 25 at 14:36











  • Ok, I´ll check. It remains below 1 with my toy data, but I´ll check with your dataset

    – Oka
    Mar 25 at 14:49










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55337926%2farea-between-the-two-curves%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














With trapezoidal rule you could probably calculate it like this:



d0 <- dens.pre
d1 <- dens.post
f0 <- approxfun(d0$x, d0$y)
f1 <- approxfun(d1$x, d1$y)

# defining x range of the density overlap
ovrng <- c(18.3, min(max(d0$x), max(d1$x)))

# dividing it to sections (for example n=500)
i <- seq(min(ovrng), max(ovrng), length.out=500)

# calculating the distance between the density curves
h1 <- f0(i)-f1(i)
h2 <- f1(i)-f0(i)

#and using the formula for the area of a trapezoid we add up the areas
area1<-sum( (h1[-1]+h1[-length(h1)]) /2 *diff(i) *(h1[-1]>=0+0)) # for the regions where d1>d0
area2<-sum( (h2[-1]+h2[-length(h2)]) /2 *diff(i) *(h2[-1]>=0+0)) # for the regions where d1<d0
area_total <- area1 + area2
area_total


Though, since you are interested only in the area where one curve remain below the other for the whole range, this can be shortened:



d0 <- dens.pre
d1 <- dens.post
f0 <- approxfun(d0$x, d0$y)
f1 <- approxfun(d1$x, d1$y)

# defining x range of the density overlap
ovrng <- c(18.3, min(max(d0$x), max(d1$x)))

# dividing it to sections (for example n=500)
i <- seq(min(ovrng), max(ovrng), length.out=500)

# calculating the distance between the density curves
h1 <- f1(i)-f0(i)

#and using the formula for the area of a trapezoid we add up the areas where d1>d0
area<-sum( (h1[-1]+h1[-length(h1)]) /2 *diff(i) *(h1[-1]>=0+0))
area

#We can plot the region using
plot(d0, main="d0=black, d1=green")
lines(d1, col="green")
jj<-which(h>0 & seq_along(h) %% 5==0); j<-i[jj];
segments(j, f1(j), j, f1(j)-h[jj])


There are other (and more detailed) solutions here and here






share|improve this answer

























  • Hi, I tried the same procedure yesterday. I got the total area between the curves. But I need area between curves after an X value 18.3, which is the area between the curves after the redline as shown in the above fig.

    – chanakya chan
    Mar 25 at 14:05











  • Hi, Thank you for the comment. I corrected the code so it will calculate after 18.3.

    – Oka
    Mar 25 at 14:33











  • Thank you very much@-Oka

    – chanakya chan
    Mar 25 at 14:35











  • @chanakya chan : Is it acceptable / sufficient solution?

    – Oka
    Mar 25 at 14:36











  • Ok, I´ll check. It remains below 1 with my toy data, but I´ll check with your dataset

    – Oka
    Mar 25 at 14:49















0














With trapezoidal rule you could probably calculate it like this:



d0 <- dens.pre
d1 <- dens.post
f0 <- approxfun(d0$x, d0$y)
f1 <- approxfun(d1$x, d1$y)

# defining x range of the density overlap
ovrng <- c(18.3, min(max(d0$x), max(d1$x)))

# dividing it to sections (for example n=500)
i <- seq(min(ovrng), max(ovrng), length.out=500)

# calculating the distance between the density curves
h1 <- f0(i)-f1(i)
h2 <- f1(i)-f0(i)

#and using the formula for the area of a trapezoid we add up the areas
area1<-sum( (h1[-1]+h1[-length(h1)]) /2 *diff(i) *(h1[-1]>=0+0)) # for the regions where d1>d0
area2<-sum( (h2[-1]+h2[-length(h2)]) /2 *diff(i) *(h2[-1]>=0+0)) # for the regions where d1<d0
area_total <- area1 + area2
area_total


Though, since you are interested only in the area where one curve remain below the other for the whole range, this can be shortened:



d0 <- dens.pre
d1 <- dens.post
f0 <- approxfun(d0$x, d0$y)
f1 <- approxfun(d1$x, d1$y)

# defining x range of the density overlap
ovrng <- c(18.3, min(max(d0$x), max(d1$x)))

# dividing it to sections (for example n=500)
i <- seq(min(ovrng), max(ovrng), length.out=500)

# calculating the distance between the density curves
h1 <- f1(i)-f0(i)

#and using the formula for the area of a trapezoid we add up the areas where d1>d0
area<-sum( (h1[-1]+h1[-length(h1)]) /2 *diff(i) *(h1[-1]>=0+0))
area

#We can plot the region using
plot(d0, main="d0=black, d1=green")
lines(d1, col="green")
jj<-which(h>0 & seq_along(h) %% 5==0); j<-i[jj];
segments(j, f1(j), j, f1(j)-h[jj])


There are other (and more detailed) solutions here and here






share|improve this answer

























  • Hi, I tried the same procedure yesterday. I got the total area between the curves. But I need area between curves after an X value 18.3, which is the area between the curves after the redline as shown in the above fig.

    – chanakya chan
    Mar 25 at 14:05











  • Hi, Thank you for the comment. I corrected the code so it will calculate after 18.3.

    – Oka
    Mar 25 at 14:33











  • Thank you very much@-Oka

    – chanakya chan
    Mar 25 at 14:35











  • @chanakya chan : Is it acceptable / sufficient solution?

    – Oka
    Mar 25 at 14:36











  • Ok, I´ll check. It remains below 1 with my toy data, but I´ll check with your dataset

    – Oka
    Mar 25 at 14:49













0












0








0







With trapezoidal rule you could probably calculate it like this:



d0 <- dens.pre
d1 <- dens.post
f0 <- approxfun(d0$x, d0$y)
f1 <- approxfun(d1$x, d1$y)

# defining x range of the density overlap
ovrng <- c(18.3, min(max(d0$x), max(d1$x)))

# dividing it to sections (for example n=500)
i <- seq(min(ovrng), max(ovrng), length.out=500)

# calculating the distance between the density curves
h1 <- f0(i)-f1(i)
h2 <- f1(i)-f0(i)

#and using the formula for the area of a trapezoid we add up the areas
area1<-sum( (h1[-1]+h1[-length(h1)]) /2 *diff(i) *(h1[-1]>=0+0)) # for the regions where d1>d0
area2<-sum( (h2[-1]+h2[-length(h2)]) /2 *diff(i) *(h2[-1]>=0+0)) # for the regions where d1<d0
area_total <- area1 + area2
area_total


Though, since you are interested only in the area where one curve remain below the other for the whole range, this can be shortened:



d0 <- dens.pre
d1 <- dens.post
f0 <- approxfun(d0$x, d0$y)
f1 <- approxfun(d1$x, d1$y)

# defining x range of the density overlap
ovrng <- c(18.3, min(max(d0$x), max(d1$x)))

# dividing it to sections (for example n=500)
i <- seq(min(ovrng), max(ovrng), length.out=500)

# calculating the distance between the density curves
h1 <- f1(i)-f0(i)

#and using the formula for the area of a trapezoid we add up the areas where d1>d0
area<-sum( (h1[-1]+h1[-length(h1)]) /2 *diff(i) *(h1[-1]>=0+0))
area

#We can plot the region using
plot(d0, main="d0=black, d1=green")
lines(d1, col="green")
jj<-which(h>0 & seq_along(h) %% 5==0); j<-i[jj];
segments(j, f1(j), j, f1(j)-h[jj])


There are other (and more detailed) solutions here and here






share|improve this answer















With trapezoidal rule you could probably calculate it like this:



d0 <- dens.pre
d1 <- dens.post
f0 <- approxfun(d0$x, d0$y)
f1 <- approxfun(d1$x, d1$y)

# defining x range of the density overlap
ovrng <- c(18.3, min(max(d0$x), max(d1$x)))

# dividing it to sections (for example n=500)
i <- seq(min(ovrng), max(ovrng), length.out=500)

# calculating the distance between the density curves
h1 <- f0(i)-f1(i)
h2 <- f1(i)-f0(i)

#and using the formula for the area of a trapezoid we add up the areas
area1<-sum( (h1[-1]+h1[-length(h1)]) /2 *diff(i) *(h1[-1]>=0+0)) # for the regions where d1>d0
area2<-sum( (h2[-1]+h2[-length(h2)]) /2 *diff(i) *(h2[-1]>=0+0)) # for the regions where d1<d0
area_total <- area1 + area2
area_total


Though, since you are interested only in the area where one curve remain below the other for the whole range, this can be shortened:



d0 <- dens.pre
d1 <- dens.post
f0 <- approxfun(d0$x, d0$y)
f1 <- approxfun(d1$x, d1$y)

# defining x range of the density overlap
ovrng <- c(18.3, min(max(d0$x), max(d1$x)))

# dividing it to sections (for example n=500)
i <- seq(min(ovrng), max(ovrng), length.out=500)

# calculating the distance between the density curves
h1 <- f1(i)-f0(i)

#and using the formula for the area of a trapezoid we add up the areas where d1>d0
area<-sum( (h1[-1]+h1[-length(h1)]) /2 *diff(i) *(h1[-1]>=0+0))
area

#We can plot the region using
plot(d0, main="d0=black, d1=green")
lines(d1, col="green")
jj<-which(h>0 & seq_along(h) %% 5==0); j<-i[jj];
segments(j, f1(j), j, f1(j)-h[jj])


There are other (and more detailed) solutions here and here







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 25 at 14:59

























answered Mar 25 at 13:55









OkaOka

7682 silver badges9 bronze badges




7682 silver badges9 bronze badges












  • Hi, I tried the same procedure yesterday. I got the total area between the curves. But I need area between curves after an X value 18.3, which is the area between the curves after the redline as shown in the above fig.

    – chanakya chan
    Mar 25 at 14:05











  • Hi, Thank you for the comment. I corrected the code so it will calculate after 18.3.

    – Oka
    Mar 25 at 14:33











  • Thank you very much@-Oka

    – chanakya chan
    Mar 25 at 14:35











  • @chanakya chan : Is it acceptable / sufficient solution?

    – Oka
    Mar 25 at 14:36











  • Ok, I´ll check. It remains below 1 with my toy data, but I´ll check with your dataset

    – Oka
    Mar 25 at 14:49

















  • Hi, I tried the same procedure yesterday. I got the total area between the curves. But I need area between curves after an X value 18.3, which is the area between the curves after the redline as shown in the above fig.

    – chanakya chan
    Mar 25 at 14:05











  • Hi, Thank you for the comment. I corrected the code so it will calculate after 18.3.

    – Oka
    Mar 25 at 14:33











  • Thank you very much@-Oka

    – chanakya chan
    Mar 25 at 14:35











  • @chanakya chan : Is it acceptable / sufficient solution?

    – Oka
    Mar 25 at 14:36











  • Ok, I´ll check. It remains below 1 with my toy data, but I´ll check with your dataset

    – Oka
    Mar 25 at 14:49
















Hi, I tried the same procedure yesterday. I got the total area between the curves. But I need area between curves after an X value 18.3, which is the area between the curves after the redline as shown in the above fig.

– chanakya chan
Mar 25 at 14:05





Hi, I tried the same procedure yesterday. I got the total area between the curves. But I need area between curves after an X value 18.3, which is the area between the curves after the redline as shown in the above fig.

– chanakya chan
Mar 25 at 14:05













Hi, Thank you for the comment. I corrected the code so it will calculate after 18.3.

– Oka
Mar 25 at 14:33





Hi, Thank you for the comment. I corrected the code so it will calculate after 18.3.

– Oka
Mar 25 at 14:33













Thank you very much@-Oka

– chanakya chan
Mar 25 at 14:35





Thank you very much@-Oka

– chanakya chan
Mar 25 at 14:35













@chanakya chan : Is it acceptable / sufficient solution?

– Oka
Mar 25 at 14:36





@chanakya chan : Is it acceptable / sufficient solution?

– Oka
Mar 25 at 14:36













Ok, I´ll check. It remains below 1 with my toy data, but I´ll check with your dataset

– Oka
Mar 25 at 14:49





Ok, I´ll check. It remains below 1 with my toy data, but I´ll check with your dataset

– Oka
Mar 25 at 14:49








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.




















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55337926%2farea-between-the-two-curves%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현