Reputation: 1489
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)
Upvotes: 1
Views: 245
Reputation: 93938
There's probably several ways, but polygon
is nice:
## define function
f <- function(x, peak_x, peak_y, coef) coef * -(x - peak_x)^ 2 + peak_y
## base plot
plot(NA, type="l", xlim=c(0,65), ylim=c(0,11))
## coordinates of user plotting space
pusr <- par("usr")
## x points to cover the whole area
x <- seq(pusr[1], pusr[2], length.out=101)
## then plot the polygons associated with the curves
rect(pusr[1], pusr[3], pusr[2], pusr[4], col=2)
polygon(x = c(x, pusr[1]), y = c(f(x, 10, 11, 0.004), pusr[3]), col="yellow")
polygon(x = c(x, pusr[1]), y = c(f(x, 10, 6, 0.003), pusr[3]), col="green")
Upvotes: 2
Reputation: 1489
The correct answer may be obtained using:
a <- curve(f,-3,65,ylim=c(0,12),xaxs="i",yaxs="i")
pusr <- par("usr")
rect(pusr[1], pusr[3], pusr[2], pusr[4], col=2,border = 1)
b <- curve(f(x, peak_y = 6,coef = .003),-3,65,add=TRUE,col=2)
polygon(c(-3,a$x,63),c(0,a$y,f(63)),col="yellow")
polygon(c(-3,b$x,54),c(-3,b$y,f(55, peak_y = 6,coef = .003)),col=3)
box()
Upvotes: 1