[R] Query: colouring graph

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Fri Oct 17 11:28:09 CEST 2003


cristian at biometria.univr.it wrote:
> Hi!
> 
> How can I fill with colors a portion of a graph (e.g.: I want fill in red the
> area within two confidence intervals)?

  You can construct the coordinates of the polygon that fills this 
region, then use 'polygon' to fill it. Here:

# first set up the plot - we want the density over the polygon,
# so make a blank plot of the right size:

x <- seq(-3,3,len=100)
plot(x,dnorm(x),type='n')

# a little function that draws a filled polygon between limits under
# dnorm(x) The polygon has to go from the axis, up, along the curve,
# then back down again.

fillDnorm <- function(low,high,col="red",n=100){
   x <- seq(low,high,len=n)
   y <- dnorm(x)
   x <- c(x[1],x,x[length(x)])
   y <- c(0,y,0)
   polygon(x,y,col=col,border=NA)
}

# fill between -2 and -1
  fillDnorm(-2,-1)

# now add the density
  lines(x,dnorm(x))

  Tweak as required.

Baz




More information about the R-help mailing list