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

Martin Maechler maechler at stat.math.ethz.ch
Thu Jun 3 14:46:07 CEST 1999

```>>>>> "Paul" == Paul Murrell <pm254 at medschl.cam.ac.uk> writes:

Paul> 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..

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

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

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

Paul> unfortunately, i don't think there's an easier way.

however, there *is*  --- using the much underused  `` type = "h" '' :

Either -- with "overplotting":

plot(sin, -pi, 2*pi, type="h", col="green", n=801)
plot(sin, 0,   2*pi, type="h", col="red"  , n=401, add=TRUE)

Or  (without "overplotting")

plot(sin, -pi, 0,  type="h", col="green", n=401,
xlim = c(-pi, 2*pi), ylim = c(-1,1))
plot(sin, 0, 2*pi, type="h", col="red"  , n=401, add=TRUE)

{Even   xlab & ylab  are ok!}

Note however, that this is less efficient from a device-driver point of
view.  E.g. with postscript(),  The file sizes are
7.1, 48.0 and 33.2 1000Bytes
for Paul's (first) example, my "overplotting" and "non-overplotting"
example, respectively.

Martin Maechler <maechler at stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/
Seminar fuer Statistik, ETH-Zentrum SOL G1;	Sonneggstr.33
ETH (Federal Inst. Technology)	8092 Zurich	SWITZERLAND
phone: x-41-1-632-3408		fax: ...-1086			<><
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```