Presentation is loading. Please wait.

Presentation is loading. Please wait.

Spatial.

Similar presentations


Presentation on theme: "Spatial."— Presentation transcript:

1 Spatial

2 Outline Types of Spatial Data R Spatial packages S4 R objects
Projections Spatial methods SpatialPoints SpatialLines/SpatialPolygons SpatialPixels SpatialPoints - Sample Dataset Importing/Exporting Spatial information and slots Displaying SpatialPolygons - Sample Dataset Reprojecting SpatialPixels - Sample Dataset Importing/Exporting rasters Deriving Thematic rasters (importing, spatial info, reclassing) Temporary files

3 Spatial Data in R ## Types of Spatial Data
Points - a set of single point locations Lines - an ordered set of points, connected by straight line segments Polygons – an area, with enclosed lines, possibly containing holes Rasters – a collection of points or rectangular cells, in grid format ## R Spatial packages sp Basic R classes for handling geospatial data maptools Read and write shapefiles. Cannot read the projection file. rgeos Interface to spatial geometry for sp objects rgdal Supports GDAL raster formats and OGR vector formats.. Retains projection information when reading and writing (PROJ.4 library) raster Spatial data analysis for rasters. ## Help links for spatial tools in R # Summary of tools for Spatial data analysis

4 Spatial Data in R # Set working directory # Load libraries
path <- "W:/Techniques/Projects/Peru/Rworkshop" setwd(path) # Load libraries library(sp) library(maptools) library(rgeos) library(rgdal) library(raster)

5 Spatial Data in R ## Spatial classes (sp package) Bivand, et al. 2008
getClass("Spatial") Bivand, et al. 2008

6 Spatial Data in R ## S4 R objects
New-style classes with formal definitions that specify the name and type of the object's components, called slots. ## The Spatial class has 2 pre-defined slots bbox – The bounding box, consisting of a matrix of coordinates defining the extent of the spatial object. proj4string – The class object defining the coordinate reference system (CRS) CRS contains datum and projection datum – a surface that represents the shape of the earth projection – renders the surface of an ellipsoid as a plane

7 Spatial Data in R ## Projections # rgdal package
PROJ.4 - Cartographic Projections Library A library of projection functions to perform respective forward and inverse transformation of cartographic data. # Format of projection string (proj4string) "+proj=prj +ellps=GRS80 +datum=datum +no_defs” # List of common projections # More proj4string options.. " +proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs" " +proj=utm +zone=13 +datum=NAD83" " +proj=utm +ellps=WGS84 +datum=WGS84 +zone=11, +units=m +towgs84=0,0,0" " +proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=23 +lon_0=-96 +x_0=0 +y_0=0 +datum=NAD83 +units=m" " +no_defs +ellps=GRS80 +towgs84=0,0,0"

8 Spatial Data in R ## Spatial methods (sp package)
## Common attributes of R objects: # method - a function associated with a particular type of object (ex. summary, print) ## Spatial methods (sp package) Bivand, et al. 2008

9 SpatialPoints Bivand, et al. 2008

10 SpatialLines/Polygons
Lists of List Objects List of Objects Object Bivand, et al. 2008

11 SpatialPixels Similar to SpatialPoints with regularly spaced coordinates. Bivand, et al. 2008

12 Sample Dataset Utah, USA

13 Sample Dataset Uinta Mountains, Utah,USA
Highest East-West oriented mountain range in the contiguous U.S. - up to 13,528 ft (4,123 m) High Uinta Wilderness ## Vegetation 5 different life zones: shrub-montane aspen lodgepole pine spruce-fir alpine

14 SpatialPoints

15 SpatialPoints - Importing/Exporting
Sample Dataset SpatialPoints - Importing/Exporting ## Import data frame with X/Y coordinates ## (FIA plot data with fuzzed/swapped coordinates) plt <- read.csv("PlotData/plt.csv", header=TRUE, stringsAsFactors=FALSE) ## Generate SpatialPoints x <- "LON" y <- "LAT" prj <- "longlat" datum <- "NAD83" prj4str <- "+proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs" ptshp <- SpatialPointsDataFrame(plt[,c(x,y)], plt, proj4string = CRS(prj4str)) class(ptshp) # Export SpatialPoints help(writeOGR) writeOGR(ptshp, "Outfolder", "ptshp", driver="ESRI Shapefile")

16 SpatialPoints – Spatial Info
Sample Dataset SpatialPoints – Spatial Info ## Get spatial information for ptshp summary(ptshp) # General info and summary statistics for attribute # data of ptshp mode(ptshp) # Get mode of ptshp class(ptshp) # Get class of ptshp is.projected(ptshp) # Check if ptshp has projection information proj4string(ptshp) # Set or get projection information str(ptshp) # Structure of ptshp

17 Sample Dataset SpatialPoints - Slots
## Get slot names and access slots for SpatialPoints slotNames(ptshp) # Get name of ptshp components (slots) # Get data frame attributes of ptshp # Get coordinates of ptshp # Get extent of ptshp # Get projection information # Get first 6 rows of data frame of ptshp dim(ptshp) # Get dimensions of data frame of ptshp

18 SpatialPoints - Displaying
Sample Dataset SpatialPoints - Displaying ## Display ptshp plot(ptshp) # Display ptshp points with red dots, half size plot(ptshp, col="RED", pch=16, cex=0.5) # Display subsets of ptshp plot(ptshp[ptshp$INVYR==2002,], col="BLUE") plot(subset(ptshp, INVYR==2003), col="RED", add=TRUE) # pch codes # Colors colors() ## Help for point graphics

19 Sample Dataset ## Exercise 1 Exercise
## 1.1 Get the min and max coordinates of the boundary of ptshp. ## 1.2 Display points where elevation (ELEVM) are >= 3000 in dark green. ## 1.3 Add points where elevation (ELEVM) are < 3000 in yellow. ## 1.4 Overlay the point with the maximum elevation (ELEVM) in red.

20 SpatialPolygons

21 Sample Dataset SpatialPolygons # SpatialPolygons – file names
# Area of Interest (AOI) boundary (Uinta Mountains, UT) aoifn <- "uintaN_aoi.shp" # National Forest System boundary within AOI nfsfn <- "uintaN_nfs.shp" # High Uinta Wilderness boundary within AOI wildfn <- "uintaN_wild.shp"

22 SpatialPolygons - Importing/Exporting
Sample Dataset SpatialPolygons - Importing/Exporting ## Importing shapefiles using OGR drivers (rgdal) ## OGR functions From the Geospatial Data Abstraction Library (GDAL), interfaced through rgdal. Reads spatial data, including the spatial reference. readOGR – reads OGR data source and layer into an R Spatial object writeOGR – writes data out using supported drivers Note: There are 2 main arguments.. that may take different forms, depending on the available drivers. dsn – data source name layer – the name of the layer Note: A driver is a software component loaded on demand to enable a device to work with a computer's operating system. ogrDrivers() help(readOGR)

23 SpatialPolygons - Import
Sample Dataset SpatialPolygons - Import ## Importing polygon shapefiles ## (AOI boundary, NFS boundary, Wilderness boundary) # dsn – data source name (folder with layers) # layer – the name of the layer (no extension) ## Set dsn dsn <- "SpatialData" ## Spatial layer names aoinm <- "uintaN_aoi" nfsnm <- "uintaN_nfs" wildnm <- "uintaN_wild" ## Import shapefiles bndpoly <- readOGR(dsn=dsn, layer=aoinm, stringsAsFactors=FALSE) nfspoly <- readOGR(dsn=dsn, layer=nfsnm, stringsAsFactors=FALSE) wildpoly <- readOGR(dsn=dsn, layer=wildnm, stringsAsFactors=FALSE)

24 SpatialPolygons – Spatial Info
Sample Dataset SpatialPolygons – Spatial Info ## Get spatial information for bndpoly bndpoly # Get general information of polygon summary(bndpoly) # Summary information for polygon mode(bndpoly) # Get mode of bndpoly typeof(bndpoly) # Get typeof class(bndpoly) # Get class of bndpoly proj4string(bndpoly) # Set or get projection information of bndpoly bbox(bndpoly) # Get extent of bndpoly dim(bndpoly) # Get dimension of bndpoly str(bndpoly) # Get structure of bndpoly

25 SpatialPolygons - slots
Sample Dataset SpatialPolygons - slots (1) (2) (3) # Get slot names for class SpatialPolygons (1) getClass("SpatialPolygons") slotNames(bndpoly) @polygons # the list of Polygons objects @plotOrder # the order to plot the Polygons @bbox # bounding box slot @proj4string # coordinate reference system slot @data # associated data frame (for class SpatialPolygonsDataFrame objects)

26 SpatialPolygons – Displaying
Sample Dataset SpatialPolygons – Displaying ## Display bndpoly plot(bndpoly) # Display polygon shapefile plot(bndpoly, col="blue") # Display polygon with blue fill color plot(bndpoly, border="red", lwd=3) # red outline and line width=3 plot(bndpoly, col="blue", border="red", lwd=3) # blue fill plot(bndpoly, col="blue", border="red", lwd=3, bg="black", axes=TRUE) # with background colored and axes labels

27 SpatialPolygons – Spatial Info
Sample Dataset SpatialPolygons – Spatial Info # Get spatial information for nfspoly nfspoly # Get general information of nfspoly summary(nfspoly) # Summary information for nfspoly dim(nfspoly) # Dimensions of nfspoly str(nfspoly) # Get structure of nfspoly

28 SpatialPolygons - slots
Sample Dataset SpatialPolygons - slots (1) (2) (3) # Get slot names for class SpatialPolygons (1) getClass("SpatialPolygons") slotNames(nfspoly) @polygons # the list of Polygons objects @plotOrder # the order to plot the Polygons @bbox # bounding box slot @proj4string # coordinate reference system slot @data # associated data frame (for class SpatialPolygonsDataFrame objects)

29 SpatialPolygons - slots
Sample Dataset SpatialPolygons - slots (1) (2) (3) # Get slot names for class Polygons (2) getClass("Polygons") # First feature # a list of rings (islands/holes) that make up the feature # the order to plot the feature # label point coordinates of the feature # unique identifier of the feature # area of the feature (in units of feature projection)

30 SpatialPolygons - slots
Sample Dataset SpatialPolygons - slots (1) (2) (3) # Get slot names for class Polygon (3) getClass("Polygon") "Polygons")[[1]]) # first ring of feature - class 'Polygon' # label point coordinates of the feature ring # area of the feature ring # coordinates of the feature ring

31 SpatialPolygons - slots
Sample Dataset SpatialPolygons - slots # Accessing slots of SpatialPolygons # Data frame attributes of shp # Get info of each polygon within Spatial Polygons # Get order of polygons within Spatial Polygons # Get extent of bndpoly # Accessing slots of Polygons slot(nfspoly, "polygons") # (2)slots slotsPolygons <- slot(nfspoly, "polygons") # (2)slots typeof(slotsPolygons) length(slotsPolygons) sapply(slotsPolygons, function(x)slot(x, "ID")) # (2)slots sapply(slotsPolygons, function(x)slot(x, "area")) # (2)slots slotsPolygon <- "Polygons") # (3)slots slotsPolygon <- "Polygons") # (3)slots

32 SpatialPolygons - Displaying
Sample Dataset SpatialPolygons - Displaying ## Display nfspoly and wildpoly plot(bndpoly, col="dark blue") plot(nfspoly, border="yellow", add=TRUE, lwd=2) plot(wildpoly, add=TRUE, border="green") # Add points – in red plot(ptshp, add=TRUE, col="red", pch=16, cex=0.5)

33 SpatialPolygons - Reprojecting
Sample Dataset SpatialPolygons - Reprojecting ## Notice, the point layer did not display. Check the projections. projection(bndpoly) projection(ptshp) ## Reproject ptshp to projection of bndpoly polyprj <- projection(bndpoly) ptshpprj <- spTransform(ptshp, CRSobj=CRS(polyprj)) projection(ptshpprj) # Add points – in red plot(ptshpprj, add=TRUE, col="red", pch=16, cex=0.5) # Add thicker boundary line plot(bndpoly, lwd=3, add=TRUE) # Add labels for nfspoly text(nfspoly, nfspoly$FORESTNAME, cex=0.75, pos=3, col="white")

34 Sample Dataset ## Exercise 2 Exercise
## 2.1 Get projection of nfspoly. ## 2.2 Display the area of interest boundary (bndpoly) with no color fill. ## 2.3 Add the wilderness boundary (wildpoly) with green fill and with no outline. ## 2.4 Get total sum of area of nfspoly.

35 SpatialPixels

36 Sample Dataset # Elevation (m) SpatialPixels
# National Elevation Dataset (NED) in meters elevfn <- "SpatialData/uintaN_elevm.img" # Elevation (m)

37 Sample Dataset # Forest/Nonforest map SpatialPixels
fnffn <- "SpatialData/uintaN_fnf.img"

38 SpatialPixels - Importing/Exporting
Sample Dataset SpatialPixels - Importing/Exporting ## Importing SpatialPixels (raster) files help(raster) elev <- raster("SpatialData/uintaN_elevm.img") elev dim(elev) class(elev) ## Importing a raster stack help(stack) rstack <- stack("SpatialData/uintaN_elevm.img", "SpatialData/uintaN_fnf.img") rstack dim(rstack) class(rstack) ## Exporting a raster help(writeRaster) writeRaster(rstack, filename="Outfolder/rstack1.img") # Add integer datatype and notice size of file writeRaster(rstack, filename="Outfolder/rstack2.img", datatype="INT1U", overwrite=TRUE)

39 SpatialPixels - Spatial Info
Sample Dataset SpatialPixels - Spatial Info ## Get spatial information for elev elev class(elev) inMemory(elev) # Checks if raster is stored in memory (RAM) unique(elev) # Get unique values of raster extent(elev) # Get extent of raster boxplot(elev) # Display boxplot of raster values dim(elev) # Get dimensions of raster res(elev) # Get the resolution of raster (x y) ncell(elev) # Number of cells of raster maxValue(elev) # Get Maximum value in raster freq(elev) # Get frequency table of raster ## Overview of functions in raster package

40 Sample Dataset SpatialPixels - slots
## Get slot names for class SpatialPixels getClass("SpatialPixels") slotNames(elev) str(elev) the source (file name) of raster list of attributes of raster the legend features of raster, if exist the title of raster, if exists the bounding box of raster number of columns of raster number of rows of raster coordinate reference system slot ## Get slot names for class SpatialPixels slots

41 SpatialPixels - Displaying
Sample Dataset SpatialPixels - Displaying ## Display rasters plot(elev) # Display with terrain colors – 4 classes plot(elev, col=terrain.colors(n=4)) # Display with terrain colors – 20 classes plot(elev, col=terrain.colors(n=20)) # Exclude axis labels plot(elev, col=terrain.colors(n=4), axes=FALSE) # Get help with other colors for continuous data help(terrain.colors) # Display elevation data with contours contour(elev)

42 SpatialPixels - Deriving
Sample Dataset SpatialPixels - Deriving ## Derive new rasters # Generate slope and aspect and hillshade from elevation dataset slp <- terrain(elev, opt=c('slope'), unit='radians') asp <- terrain(elev, opt=c('aspect'), unit='radians') hill <- hillShade(slope, asp) # Generate hillshade # Display hillshade in grey scale plot(hill, col=grey(0:100/100), legend=FALSE) # Classify raster elevcl <- cut(elev, breaks=5) # 5 classes plot(elevcl) # Display classified raster cols <- c("brown", "palegreen", "orange1", "dark green", "snow") plot(elevcl, col=cols, breaks=c(0:5)) # Converts raster from meters to feet elevft <- elev * summary(elev) summary(elevft)

43 Sample Dataset SpatialPixels - fnf
## Get spatial information for fnf (thematic raster) fnf <- raster("SpatialData/uintaN_fnf.img") unique(fnf) # Get unique values of raster extent(fnf) # Get extent of raster barplot(fnf) # Display barplot of raster values ## Display fnf fnfvals <- sort(unique(fnf)) plot(fnf, breaks=fnfvals, col=c("green", "brown", "blue"), legend=TRUE) ## Overview of functions in raster package

44 Sample Dataset reclass raster ## Reclass raster layer to 2 categories
help(reclassify) fromvect <- c(0,1,2,3) tovect <- c(2,1,2,2) rclmat <- matrix(c(fromvect, tovect), 4, 2) fnfrcl <- reclassify(x=fnf, rclmat) fnfrcl unique(fnfrcl) freq(fnfrcl) ## To save to file help(writeRaster) stratrcl <- reclassify(x=fnf, rclmat, datatype='INT2U', filename="SpatialData/uintaN_fnfrcl.img", overwrite=TRUE) ## Plot new reclassed raster fnfrclvals <- c(0, unique(fnfrcl)) plot(fnfrcl, breaks=fnfrclvals, col=c("green","brown"), legend=TRUE) barplot(fnfrcl)

45 Temporary Files ## Note:
Functions in raster package create temporary files if the values of an output RasterLayer cannot be stored in memory (RAM). This can happen when no filename is provided to a function an in functions where you cannot provide a filename. Temporary files are automatically removed at the start of each session. ## During session: showTmpFiles() removeTmpFiles() ## You can change where the temporary folder is in the Rprofile.site file. ## (C:\Program Files\R\R-3.0.0\etc\Rprofile.site) # Added options(scipen=6) options(rasterTmpDir='c:/Temp/') rasterOptions() rasterOptions(chunksize = 1e+04, maxmemory = 1e+06)

46 Sample Dataset ## Exercise 3 Exercise
## 3.1 Get the minimum value of elev ## 3.2 Display elev raster with heat colors and 10 classes ## 3.3 Generate slope (in degrees) ## 3.4 Classify the slope raster from 3.3 into 4 classes ## 3.5 Display the classified slope raster with unique colors. Use colors() to select color choices. Exclude axes labels.

47 Spatial Help Links # Summary of tools for Spatial data analysis
# Presentation – Introduction to representing spatial objects in R – Roger Bivand # List of common projections ## Help for point graphics ## Overview of functions in raster package


Download ppt "Spatial."

Similar presentations


Ads by Google