[R] drawing direction fields

Jim Lemon jim at bitwrit.com.au
Wed Oct 31 10:26:57 CET 2007


Jong-Hoon Kim wrote:
> Dear useRs,
> 
> I am trying to draw direction fields for some differential equations.
> So for I couldn't find much information on that.  Could anybody give
> me a hint how to draw a direction field using R?
> 
Hi Jong-Hoon,

Here's a start on a function.

direction.field<-function(dydx,xlim=c(-1,1),ylim=c(-1,1),
  nxarrows=20,nyarrows=20,length=NA) {

  xinc<-diff(xlim)/(nxarrows*2)
  yinc<-diff(ylim)/(nyarrows*2)
  if(is.na(length)) length<-par("pin")[1]/100
  plot(0,xlim=xlim,ylim=ylim,type="n")
  for(x in seq(xlim[1]+xinc,xlim[2]-xinc,length=nxarrows)) {
   for(y in seq(ylim[1]+yinc,ylim[2]-yinc,length=nyarrows)) {
    stan<-atan(eval(parse(text=dydx)))
    arrows(x-xinc*cos(stan),y-yinc*sin(stan),
     x+xinc*cos(stan),y+yinc*sin(stan),
     length=length)
   }
  }
}
direction.field("0*x+1*y")

Jim



More information about the R-help mailing list