[R] Plotting Vector Fields

Tomas Bacigal tom67t at azet.sk
Wed Nov 28 12:10:57 CET 2007

Plotting vector fields as we know it from Wolfram Mathematica's
PlotVectorField[{f1(x1), f2(x2)}, {x1, min, max}, {x2, ymin, ymax},
PlotPoints -> ...]


#! 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
# Combinations of "x" and "y" are expanded into vectors of length n*m,
# n = length(x), m = length(y) and this ordering is preserved also in
# 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,

#! 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,]
k <- min( maxlength / c(max(abs(dx)),max(abs(dy))) )
x1 <- x0 + k*dx
y1 <- y0 + k*dy
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)


plotVectorField(function(x1,x2) c(x2,-x1), c(-1,1), c(-1,1), 9)

Tomas Bacigal

-------Original message --------
From: bb2 at duke.edu
Date: Fri 25 Jul 2003 - 10:47:03 EST

> Message-id: <p05210600bb462c774495@[]>

> 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

More information about the R-help mailing list