修订版 | f86ada8e26102d800f0da7be1ba831eb3dc67da7 (tree) |
---|---|
时间 | 2007-12-03 19:41:45 |
作者 | iselllo |
Commiter | iselllo |
I added the code plot-vector.R. It is taken from R mailing list and it
shows how to draw a vector field using R.
@@ -0,0 +1,50 @@ | ||
1 | +### FUNCTION DEFINITION | |
2 | + | |
3 | +#! Outer product with vector function ### | |
4 | +# expand.outer joins functionality of "expand.grid" and "outer", so that | |
5 | +# a vector function can be applied, values of which are then stored in | |
6 | +# collumns. | |
7 | +# Combinations of "x" and "y" are expanded into vectors of length n*m, | |
8 | +# where | |
9 | +# n = length(x), m = length(y) and this ordering is preserved also in | |
10 | +#'values'. | |
11 | +# Matrix of values (list item 'values') and expanded variables (list | |
12 | +#items 'x','y') are returned. | |
13 | + | |
14 | +expand.outer <- function(x, y, vecfun) { | |
15 | +xy.pairs <- expand.grid(x=x, y=y, KEEP.OUT.ATTRS = FALSE) | |
16 | +x.exp <- xy.pairs$x | |
17 | +y.exp <- xy.pairs$y | |
18 | +list(values=matrix(vecfun(x.exp,y.exp), nrow=2, byrow=TRUE), x=x.exp, | |
19 | +y=y.exp) | |
20 | +} | |
21 | + | |
22 | +#! vector field plot function | |
23 | +# grid.points can be defined for both axes at once or separately | |
24 | + | |
25 | +plotVectorField <- function(vecfun, xlim, ylim, grid.points) { | |
26 | +gp <- if(length(grid.points)>1) grid.points else rep(grid.points,2) | |
27 | +maxlength <- c(diff(xlim),diff(ylim))/(gp-1)*0.9 | |
28 | +#prepare data | |
29 | +x0 <- seq(xlim[1], xlim[2], length=gp[1]) | |
30 | +y0 <- seq(ylim[1], ylim[2], length=gp[2]) | |
31 | +xy.data <- expand.outer(x0, y0, vecfun) | |
32 | +x0 <- xy.data$x | |
33 | +y0 <- xy.data$y | |
34 | +dx <- xy.data$values[1,] | |
35 | +dy <- xy.data$values[2,] | |
36 | +#scale | |
37 | +k <- min( maxlength / c(max(abs(dx)),max(abs(dy))) ) | |
38 | +x1 <- x0 + k*dx | |
39 | +y1 <- y0 + k*dy | |
40 | +#plot | |
41 | +plot.default(range(x0,x1), range(y0,y1), main="Vector field", xlab="", | |
42 | +ylab="", type="n", frame.plot=F) | |
43 | +arrows(x0,y0,x1,y1,length = 0.08, angle = 20, code = 2) | |
44 | +} | |
45 | + | |
46 | +### FUNCTION CALL | |
47 | + | |
48 | +plotVectorField(function(x1,x2) c(x2,-x1), c(-1,1), c(-1,1), 9) | |
49 | + | |
50 | + |