Home > Software design >  Coloring 3 regions of a plot in R
Coloring 3 regions of a plot in R

Time:11-19

I have a plot in which there are two curved lines (below).

I was wondering if there is way to color above the top line in red, between the two lines in yellow, and below the bottom line in green?

My desired plot as well as my reproducible code is below.

f <- function(x,peak_x=10,peak_y=11,coef=.004) coef*-(x-peak_x)^2 peak_y
a <- curve(f,0,65,ylim=c(0,11))
b <- curve(f(x, peak_y = 6,coef = .003),0,65, col=3,add=TRUE)

enter image description here

CodePudding user response:

There's probably several ways, but polygon is nice:

plot(NA, xlim=c(0,65), ylim=c(0,11))
pusr <- par("usr")

f <- function(x,peak_x=10,peak_y=11,coef=.004) coef*-(x-peak_x)^2 peak_y
x <- seq(pusr[1], 100, length.out=50)

rect(pusr[1], pusr[3], pusr[2], pusr[4], col="blue")
polygon(c(x, pusr[1]), f(c(x, pusr[2]), peak_x=10, peak_y=11, coef=0.003), col="green")
polygon(c(x, pusr[1]), f(c(x, pusr[2]), peak_x=10, peak_y=6,  coef=0.004), col="red")

box()

enter image description here

  • Related