How to Plot Speed Vectors (x, y)

First simulate some random (x,y) locations and some random speeds.

x = seq(10, 15, by = 0.25)
y = seq(40, 50, by = 0.25)
u = matrix(runif(length(x) * length(y), -2, 3), nrow = length(x), ncol = length(y))
v = matrix(runif(length(x) * length(y), -2, 3), nrow = length(x), ncol = length(y))

# melt for plotting
library(reshape2)
u <- melt(u, value.name = "u")
v <- melt(v, value.name = "v")
wind <- merge(u, v)
wind$x <- x[wind[, 1]]
wind$y <- y[wind[, 2]]
str(wind)
## 'data.frame':    861 obs. of  6 variables:
##  $ Var1: int  1 1 1 1 1 1 1 1 1 1 ...
##  $ Var2: int  1 10 11 12 13 14 15 16 17 18 ...
##  $ u   : num  1.95 -1.09 1.94 2.63 -1.7 ...
##  $ v   : num  -1.754 0.797 2.004 0.206 -1.774 ...
##  $ x   : num  10 10 10 10 10 10 10 10 10 10 ...
##  $ y   : num  40 42.2 42.5 42.8 43 ...

Look at some of the simulated data

head(wind)
##   Var1 Var2      u       v  x     y
## 1    1    1  1.948 -1.7535 10 40.00
## 2    1   10 -1.094  0.7965 10 42.25
## 3    1   11  1.944  2.0035 10 42.50
## 4    1   12  2.626  0.2061 10 42.75
## 5    1   13 -1.703 -1.7741 10 43.00
## 6    1   14 -1.003  2.2878 10 43.25

The 'wind' data frame now has some random locations in x,y and for each location there is a random speed in the x direction, u, and one in the y direction, v.

Let’s Plot This!

This code plots out the data frame show velocities as a bunch of arrows. Each arrow starts at the (x,y) location of the point, and goes in the proper direction. It's length is in whatever units u and v are in, as adjusted by the scaler constant.

require(ggplot2)
## Loading required package: ggplot2
require(grid)
## Loading required package: grid
scaler <- 1  # Use this to change unit. E.g., from meters per minute to meters per second.

p <- ggplot(wind, aes(x = x, y = y, xend = x + u * scaler, yend = y + v * scaler)) + 
    geom_segment(arrow = arrow())
print(p)

plot of chunk Plot_Velocity_Field