[R] How to fill the aerea under a plot?

Paul Murrell pm254 at medschl.cam.ac.uk
Thu Jun 3 09:58:00 CEST 1999


hi

>I plot a function, e.g.
>plot(sin, -pi, 2*pi).
>
>
>Then I would like to have the aerea
>from the x-axis up to the graph
>from x ranging from -3 to 0, shaded
>red and the other part (x from 0 to 6) under
>the graph e.g. green or sth. like that..

plot(sin, -pi, 2*pi) just draws a series of straight lines to approximate
the sine curve (but enough lines so that it looks like a smooth curve).  one
way to do what you want is to draw the lines yourself using polygon(), which
can then be filled.  the code below gives an example for your case (there
are two examples because i'm not sure what you mean by "from the x-axis up
to the graph") ...

plot(c(-pi, 2*pi), c(-1,1), type="n", ylab="sin(x)", xlab="x")
x1 <- seq(-pi, 0, length=101)
x2 <- seq(0, 2*pi, length=101)
polygon(c(0, -pi, x1), c(0, 0, sin(x1)), col="red")
polygon(c(0, 2*pi, x2), c(0, 0, sin(x2)), col="green")

plot(c(-pi, 2*pi), c(-1,1), type="n", ylab="sin(x)", xlab="x")
x1 <- seq(-pi, 0, length=101)
x2 <- seq(0, 2*pi, length=101)
polygon(c(0, -pi, x1), c(-1, -1, sin(x1)), col="red")
polygon(c(2*pi, 0, x2), c(-1, -1, sin(x2)), col="green")

unfortunately, i don't think there's an easier way.   hope this helps :)

paul


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list