Quantcast
Channel: r software hub
Viewing all articles
Browse latest Browse all 1015

Variography with gstat and ggplot2

$
0
0

By Bart Rogiers

Last year I wrote a short demo on variography with gstat and ggplot2 for a colleague who was planning to migrate to R. Just thought I’d share this here (with some additional stuff) as it might be useful for other people as well.

First, make sure you have the necessary packages installed and loaded:

require('gstat')
## Loading required package: gstat
require('sp')
## Loading required package: sp
require('ggplot2')
## Loading required package: ggplot2
The sp package is not really required, but it makes working with spatial data a little bit easier.
I like to work with the black & white ggplot2 theme, and legends positioned above the graphs, so I always adjust the basic settings the following way:


theme_set(theme_bw())


theme_update(legend.position='top')
Let’s create some synthetic data to work with. I’m using gstat here to simulate a random field on a 100×100 regular grid:
x  1:100 
y 1:100
dat expand.grid(x=x,y=y)
dat$z 1
coordinates(dat) ~x+y
gridded(dat) TRUE
g gstat(id='z',formula=z~1,model=vgm(0.9,'Sph',60,0.1,anis=c(45,0.1)),data=dat,dummy=TRUE,beta=0,maxdist=20,nmax=10)
dat data.frame(predict(g,newdata=dat,nsim=1))
## [using unconditional Gaussian simulation]
names(dat)[3]  'z'
head(dat)
##   x y           z
## 1 1 1 1.36694227
## 2 2 1 0.58134568
## 3 3 1 0.04314338
## 4 4 1 0.24155909
## 5 5 1 -0.23566363
## 6 6 1 -0.58667780

Plotting data on a regular grid is easily achieved with geom_raster():

ggplot(dat,aes(x=x,y=y,fill=z)) + geom_raster() + scale_fill_gradientn(colours=rainbow(7))
This is the data we will perform some variography on. Alternatively, have a look at this file to load your own data. We’ll transform our data frame into a spatial points data frame, and create a gstat object:
coordinates(dat)  ~x+y 
I commented the above line, as there is an issue with gstat 1.1-0, which basically mirrors gridded data horizontally before deriving the experimental variogram. Edzer Pebesma, the author of gstat, …read more

Source:: r-bloggers.com


Viewing all articles
Browse latest Browse all 1015

Trending Articles