[R] Shade area under curve?

Marcus Eger eger.m at gmx.de
Wed Jan 30 16:57:05 CET 2002


Hi,
I've written a small function "fill" that can be called after a plot(x,y) 
call. There might be simpler ways, but it works.
Ciao
Marcus

"fill" <-  function 
(x,y,ref=0,xlim=NULL,set.na=NA,log=NULL,limit.y="lower",...) {
  if (missing(y)) {
    y <- x
    x <- 1:length(x)
  }
  log <- if(is.null(log)) getlog()
  xlim <- if (is.null(xlim)) range(x) else xlim
  ix <- limit(x,lower=xlim[1],upper=xlim[2],index=T,equal=T)
  x <- x[ix]
  switch(limit.y,
         "lower"={y <- limit(Re(y[ix]),lower=ref)},
         "upper"={y <- limit(Re(y[ix]),upper=ref)}
         )
  x <- c(x[1],x,last(x))
  y[is.na(y)] <- set.na
  y <- c(ref,y,ref)
  polygon(x,y,...)

}
"getlog" <-  function () {
  x <- if (par()$xlog) "x"
  y <- if (par()$ylog) "y"
  x%+%y
}
"last" <-  function (x) {
  x[length(x)]
}
"limit" <-  function (arr,lower=min(arr),upper=max(arr),index=F,...) {
  if (index) return(betwval(arr,lower,upper,index=T,...))
 ixl <- which(arr < lower)
  ixu <- which(arr > upper)
  arr[ixl] <- lower
  arr[ixu] <- upper
  arr
}
"betwval" <-  function (arr,val1,val2,sort=F,equal=F,index=F) {
  n <- length(arr)
  if (sort) aux <- arr[order(arr)] else aux <- arr
  if (missing(val2)) {  #then it is a range
    val2 <- val1[2]
    val1 <- val1[1]
  }
  if(equal) ix <- where((aux >= val1) & (aux <= val2))
  else ix <- where((aux > val1) & (aux < val2))
  if (ix != -1)
    if(index) return(ix) else return(aux[ix])
  if(!index) return(NA) else return(ix)
}





On Wednesday 30 January 2002 16:20, Robert Lundqvist wrote:
> Hi all,
>
> I've got this graphics question which really should be easy. I want to
> shade an area between bounds under a curve. A suitable beginning seems to
> be the
>
> following:
> > plot(dnorm,-4,4)
> > segments(-4,0,4,0)
> > segments(-2,0,-2,dnorm(-2))
> > segments(2,0,2,dnorm(2))
>
> It is the area between -2 and 2 which I want to shade (or something
> similar). Hints anyone?
>
> Robert

-- 
+-------------------------------------------------------
| Dr.-Ing. Marcus Eger
| Philipps Universitaet Marburg
| Fachbereich Physik AG Neurophysik
| Renthof 7
| 35032 Marburg
| Tel. ++49 +6421 282-4169
| Fax  ++49 +6421 282-7034
+-------- ><> -------------------------------------------
| E-Mail: eger.m at gmx.de (NEW)
|         marcus.eger at physik.uni-marburg.de (OLD)
| WWW:    http://neuro.physik.uni-marburg.de/~eger (NEW)
+--------------------------------------------------------
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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