title: calculate and plot vector field of an arbitrary rasterLayer
body: <h1>Problem statement:</h1>
  <p>With <code>ggquiver::geom_quiver()</code> we can plot vector fields, provided we know <code>x</code>, <code>y</code>, <code>xend</code>, and <code>yend</code>.</p>
  <ol>
  <li>How can I calculate these parameters for an arbitrary <code>RasterLayer</code> of elevations?</li>
  <li>How can I ensure that the size of these arrows indicates the slope for that particular vector such that the arrows appear different lengths proportional to the gradient at that location (e.g., the first plot below)?</li>
  </ol>
  <hr />
  <h1>Background:</h1>
  <pre><code># ggquiver example
  
  library(tidyverse)
  library(ggquiver)
  expand.grid(x=seq(0,pi,pi/12), y=seq(0,pi,pi/12)) %&gt;%
    ggplot(aes(x=x,y=y,u=cos(x),v=sin(y))) +
    geom_quiver()
  </code></pre>
  <p><a href="https://i.stack.imgur.com/noXka.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/noXka.png" alt="enter image description here" /></a></p>
  <p>A related appraoch uses <code>rasterVis::vectorplot</code>, which relies on <code>raster::terrain</code> (provided the field units == CRS units) to calculate and plot a vector field. <a href="https://github.com/oscarperpinan/rastervis/blob/master/R/vectorplot.R" rel="nofollow noreferrer">Source code is here</a>.</p>
  <pre><code>library(raster)
  library(rasterVis)
  r &lt;- getData('alt', country='FRA', mask=TRUE)
  r &lt;- aggregate(r, 20)
  vectorplot(r, par.settings=RdBuTheme())
  </code></pre>
  <p><a href="https://i.stack.imgur.com/MMFMa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MMFMa.png" alt="enter image description here" /></a></p>
  <hr />
  <h1>Conclusion:</h1>
  <p>To review, I'd like to take an arbitrary <code>rasterLayer</code> of elevation, convert it to a <code>data.frame</code>, calculate the <code>x</code>, <code>y</code>, <code>xmax</code>, and <code>ymax</code> components of an elevation vector field that size the arrows such that they show the relative slope at the point (as in plots 1 and 2 above), and plot with <code>ggquiver</code>. Something like:</p>
  <pre><code>names(r) &lt;- &quot;z&quot;
  rd &lt;- as.data.frame(r, xy=TRUE)
  
  # calculate x, y, xend, yend for gradient vectors, add to rd, then plot
  
  ggplot(rd) + 
    geom_raster(aes(x, y, fill = z)) + 
    geom_quiver(aes(x, y, xend, yend))
  </code></pre>