Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shade area between 2 curves

Tags:

plot

r

I can't seem to wrap my mind arround how polygon() works. I've searched a lot but I cant seem to understand how polygon wants the x,y points and what do they represent.

Could someone please help me and explain how to shade for example the area between the red and blue line

curve(x/2, from=0 , to =1, col="darkblue")
curve(x/4, from=0 , to =1, add=T, col="darkred")

Thanks a lot

like image 522
ECII Avatar asked Jan 17 '23 15:01

ECII


1 Answers

Because, in this case, there isn't really any curve to the line you could use something very simple (that highlights how polygon works).

x <- c(0,1,1,0)
y <- c(x[1:2]/2, x[3:4]/4)
polygon(x,y, col = 'green', border = NA)

Now, if you had a curve you'd need more vertices.

curve(x^2, from=0 , to =1, col="darkblue")
curve(x^4, from=0 , to =1, add=T, col="darkred")
x <- c(seq(0, 1, 0.01), seq(1, 0, -0.01))
y <- c(x[1:101]^2, x[102:202]^4)
polygon(x,y, col = 'green', border = NA)

(extend the range of that last curve and see how using similar code treats the crossing curves yourself)

like image 89
John Avatar answered Jan 25 '23 15:01

John