-1

I see a great answer for drawing a polygon at the overlap of two curves HERE. But I wonder what if we want to shade part of (not the entire of) the overlap limited between say 0 and 2 (as shown in the pic below)?

I tried the following without success:

a <- curve(dnorm(x), -4, 6, panel.l = abline(v = c(0, 2), col = 1:2))
b <- curve(dnorm(x, 2), add = TRUE, col = 2)

x <- a$x[a$x >= 0 & a$x <= 2]

polygon(x, c(a$y[x], b$y[x]), col = 4)

enter image description here

rnorouzian
  • 7,397
  • 5
  • 27
  • 72

1 Answers1

-1

The idea is to give proper vertices. a$y[x] is wrong as x does not hold indices but values.

Instead you want to find the intersection by pairwise minimum function and further subset it to fit within desired range. pmin(a$y, b$y)[a$x >= xaxis_cut_1 & a$x <= xaxis_cut_2]

You also want to account for some free vertices that get excluded from above intersection hence append the x and y vectors accordingly.


x = c(xaxis_cut_1,a$x[a$x >= 0 & a$x <= 2],xaxis_cut_2)
y = c(0, pmin(a$y, b$y)[a$x >= xaxis_cut_1 & a$x <= xaxis_cut_2],0 )

Full code

# your points on xaxis:
xaxis_cut_1 = 0 ; xaxis_cut_2 = 2 ; 

# your code for curves
a <- curve(dnorm(x), -4, 6, panel.l = abline(v = c(xaxis_cut_1, xaxis_cut_2), col = 1:2))
b <- curve(dnorm(x, 2), add = TRUE, col = 2)

# calculate the desired area with a pairwise min or max function (pmin / pmax). subset the curve values on the basis of your desired x-axis range

polygon(x, y, col = 4)

here is the plot

Community
  • 1
  • 1
dSH
  • 26
  • 3