Plotting vector fields as we know it from Wolfram Mathematica's PlotVectorField[{f1(x1), f2(x2)}, {x1, min, max}, {x2, ymin, ymax}, PlotPoints -> ...]
### FUNCTION DEFINITION #! Outer product with vector function ### # expand.outer joins functionality of "expand.grid" and "outer", so that # a vector function can be applied, values of which are then stored in collumns. # Combinations of "x" and "y" are expanded into vectors of length n*m, where # n = length(x), m = length(y) and this ordering is preserved also in 'values'. # Matrix of values (list item 'values') and expanded variables (list items 'x','y') are returned. expand.outer <- function(x, y, vecfun) { xy.pairs <- expand.grid(x=x, y=y, KEEP.OUT.ATTRS = FALSE) x.exp <- xy.pairs$x y.exp <- xy.pairs$y list(values=matrix(vecfun(x.exp,y.exp), nrow=2, byrow=TRUE), x=x.exp, y=y.exp) } #! vector field plot function # grid.points can be defined for both axes at once or separately plotVectorField <- function(vecfun, xlim, ylim, grid.points) { gp <- if(length(grid.points)>1) grid.points else rep(grid.points,2) maxlength <- c(diff(xlim),diff(ylim))/(gp-1)*0.9 #prepare data x0 <- seq(xlim[1], xlim[2], length=gp[1]) y0 <- seq(ylim[1], ylim[2], length=gp[2]) xy.data <- expand.outer(x0, y0, vecfun) x0 <- xy.data$x y0 <- xy.data$y dx <- xy.data$values[1,] dy <- xy.data$values[2,] #scale k <- min( maxlength / c(max(abs(dx)),max(abs(dy))) ) x1 <- x0 + k*dx y1 <- y0 + k*dy #plot plot.default(range(x0,x1), range(y0,y1), main="Vector field", xlab="", ylab="", type="n", frame.plot=F) arrows(x0,y0,x1,y1,length = 0.08, angle = 20, code = 2) } ### FUNCTION CALL plotVectorField(function(x1,x2) c(x2,-x1), c(-1,1), c(-1,1), 9) Tomas Bacigal -------Original message -------- From: [EMAIL PROTECTED] Date: Fri 25 Jul 2003 - 10:47:03 EST > Message-id: <[EMAIL PROTECTED]> > Dear R List, > Is there a function to plot vector fields in R? > I'm looking for something similar to PlotVectorField in Mathematica > (see below), e.g. given functions f(x) and f(y), I would like to plot > the resulting field of vectors (f(x),f(y)) over some range of x and y. > PlotVectorField[{f(x), f(y)}, {x, xmin, xmax}, {y, ymin, ymax}] > Thanks for your help, > Brian ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.