[R] shading between two smoothed curves

Graves, Gregory ggraves at sfwmd.gov
Fri Aug 14 19:38:11 CEST 2009

Here is the solution for shading under a curve

attach(cars)  #example dataset
scatter.smooth(speed, dist,family = "gaussian",span = .3, xlim=c(3,25), type='n')  #plot a curve (smoothed line)
gg<-loess.smooth(speed,dist,family = "gaussian",span = .3)  #put coordinates of smoothed line into 'gg'
DF<-data.frame(gg) #convert gg into a dataframe; this dataframe has 50 rows
DF[51,]<-c(25,0)  #add a 51st row with the desired bottom right corner of the polygon under the curve
DF[52,]<-c(3,0)   #add a 52nd row with the desired bottom left corner of the polygon under the curve 
polygon(c(DF), col="gray", border = "red")  # the shading

Here is NOT the solution for shading between 2 curves [I am going to use a crayon].

#put 2 curves on the graph
scatter.smooth(speed, dist+25,family = "gaussian",span = .3,xlim=c(3,25),type='n',ylim=c(0,120))  
scatter.smooth(speed, dist-5,family = "gaussian",span = .3,xlim=c(3,25),type='n',ylim=c(0,120))
#get the xy coords of the 2 curves
gg1<-loess.smooth(speed,dist+25,family = "gaussian",span = .3)
gg2<-loess.smooth(speed,dist-5,family = "gaussian",span = .3)
#stick the xy's into a dataframe and combine the 2 dataframes
DFnew<-do.call("rbind", list(DF1, DF2))
polygon(c(DFnew), col="gray", border = "red")

Gregory A. Graves
Lead Scientist
Everglades REstoration COoordination and VERification (RECOVER) 
Watershed Division
South Florida Water Management District
Phones:  DESK: 561 / 682 - 2429 
             CELL:  561 / 719 - 8157

-----Original Message-----
From: Jim Lemon [mailto:jim at bitwrit.com.au] 
Sent: Friday, August 14, 2009 8:47 AM
To: Graves, Gregory
Cc: r-help at r-project.org
Subject: Re: [R] shading between two smoothed curves

Graves, Gregory wrote:
> I will attempt to distill my problem down to a simpler one, the solution of which will hopefully lead me to the nirvana of complete understanding, i.e., inserting a polygon beneath an irregular line terminated by the x axis.
> I 'know' that polygon will work -provided- I knew the xy coordinates of the line(s) beneath which I desire to create the polygon.  Unfortunately, I don't know how to get at that info.
> Below is an example of a irregular line for which the xy coordinates are not known (i.e., at least not by me).  I assume my problem boils down to finding out how to extract the xy from that line.  
> attach(cars)
> plot(dist ~ speed)
> scatter.smooth(speed, dist,family = "gaussian",span = .2)
Hi Gregory,
That's right, just call the underlying function (loess.smooth) and use 
"str" on the result. There should be x and y components that can be 
passed to "lines".


More information about the R-help mailing list