[R] Filled step-function?

Jim Lemon jim at bitwrit.com.au
Wed May 16 14:37:15 CEST 2007


Beate Kowalczyk wrote:
> Hello,
> 
> I'd like to generate a filled step-function in R as you can see in the 
> attachement (image is generated by grapher, but I need a freely 
> available alternative). The problem is, that I don't know, how to fill 
> it up. My code right now looks like this:
> 
> pH <- c(0,6.1,6.1,6.3,6.6,7.3,0)
> Tiefe <- c(0,0,10,40,80,120,10)
> plot(pH,Tiefe,type="s",main="Tiefenfunktion pH",ylim=c(120,0),xlim=c(0,23))
> 
Hi Beate,
If I understand this, you want the steps to be converted into a polygon 
and displayed instead of the plot "step" display. You also want the y 
axis reversed. This might do what you want:

stepfun.polygon<-function(x,y,miny=min(y),col=NULL,...) {
  plot(x,y,ylim=c(max(y),min(y)),type="n",...)
  polyx<-c(x[1],rep(x[2:length(x)],each=2),x[1])
  polyy<-c(rep(y,each=2))
  polygon(polyx,polyy,col=col)
}

Note that you will probably only want the observed values of x and y, as 
the zeros on the end produce an unwanted spike in the polygon.

Jim



More information about the R-help mailing list