0

I am attempting to plot a colored grid of attributes over a base map. Similar questions have been asked here, including one recent question I asked myself, but earlier solutions have usually involved ggplot2. I am hoping to find a solution ideally without using ggplot2 if only because my final actual map will be quite complex and I have made substantial progress so far using plot.

Below is code that plots Colorado and creates a grid of fake attribute data. I can convert the grid into spatial points using SpatialPoints and plot those points. However, I suspect I need to convert to spatial polygons, perhaps using SpatialPolygons. When I attempt to use SpatialPolygons I obtain the error shown below.

Once I get the grid cell layer added to the map I would like to crop the grid to only be displayed within Colorado (or, for example, within Colorado and Wyoming if I added another state to the map and used a larger attribute grid). However, that perhaps is a follow-up question.

Here is an earlier question with an answer using plot, but requesting additional information from the poster: R Plot Filled Longitude-Latitude Grid Cells on Map

Here is a similar earlier question from myself that only has a ggplot2 solution: color grid cells in the United States and Canada

My approach below is based off of a solution to another of my earlier questions: R: creating a map of selected Canadian provinces and U.S. states

Thank you for any help.

library(rgdal)
library(maptools)
library(ggplot2)
library(plyr)
library(RColorBrewer)
library(classInt)
library(raster)

#                  NW(long,lat)  SE(long,lat)
 mapExtent <- rbind(c(-115, 43), c( -97, 35)) 

# assign projection
newProj <- CRS("+proj=longlat +datum=NAD83 +no_defs +ellps=GRS80 +towgs84=0,0,0")

## Project map extent
mapExtentPr <- spTransform(SpatialPoints(mapExtent, 
                  proj4string=CRS("+proj=longlat")), newProj)

us1      <- getData('GADM', country="USA", level=1)
colorado <- us1[(us1$NAME_1 %in% c('Colorado')),]

## Project Colorada layer
coloradoPr  <- spTransform( colorado, newProj) 

# Create grid cells containing fake attribute data 
# using approach found here: 
# http://www.numbertheory.nl/2011/11/08/drawing-polar-centered-spatial-maps-using-ggplot2/

set.seed(1234)

xlim = c(-113, -99)
ylim = c(  35,  45)

dat.grid = expand.grid(x = xlim[1]:xlim[2], y = ylim[1]:ylim[2])
dat.grid$z = runif(nrow(dat.grid))

## Project grid layer
dat.gridPr  <- spTransform(SpatialPoints(  dat.grid, proj4string=CRS("+proj=longlat")), newProj)
dat.gridPr2 <- spTransform(SpatialPolygons(dat.grid, proj4string=CRS("+proj=longlat")), newProj)

#Error in spTransform(SpatialPolygons(dat.grid, proj4string = CRS("+proj=longlat")),  : 
#  error in evaluating the argument 'x' in selecting a method for function 'spTransform': Error in SpatialPolygons(dat.grid, proj4string = CRS("+proj=longlat")) : 
#  cannot get a slot ("area") from an object of type "integer"

## Plot each projected layer, beginning with the projected extent
plot(mapExtentPr, pch=NA)
plot(coloradoPr , border="white", col="lightgrey", add=TRUE)
plot(dat.gridPr , border="white", col="lightgrey", add=TRUE)
plot(dat.gridPr , fill=dat.grid$z, add=TRUE)
plot(dat.gridPr , fill=dat.gridPr$z, add=TRUE)

EDIT

This post describes how to add grid cells one at a time, which I could do if need be:

https://gis.stackexchange.com/questions/18311/instantiating-spatial-polygon-without-using-a-shape-file-in-r

Community
  • 1
  • 1
Mark Miller
  • 12,483
  • 23
  • 78
  • 132

1 Answers1

0

Here is code to create a color-coded grid using the sp package. I have not included the code to create the map of Colorado since that code is presented above. Also, I have not yet tried to crop the grid to fill Colorado only. That may be a separate question.

library(rgdal)
library(maptools)
library(ggplot2)
library(plyr)
library(RColorBrewer)
library(classInt)
library(raster)

setwd('c:/users/mark w miller/gis_in_R')

# create grid of polygons

grd <- GridTopology(c(1,1), c(1,1), c(10,10))
polys <- as(grd, "SpatialPolygons")

row.names(polys)

#  [1] "g1"   "g2"   "g3"   "g4"   "g5"   "g6"   "g7"   "g8"   "g9"   "g10"  "g11"  "g12"  "g13"  "g14"  "g15"  "g16"  "g17"  "g18"  "g19" 
# [20] "g20"  "g21"  "g22"  "g23"  "g24"  "g25"  "g26"  "g27"  "g28"  "g29"  "g30"  "g31"  "g32"  "g33"  "g34"  "g35"  "g36"  "g37"  "g38" 
# [39] "g39"  "g40"  "g41"  "g42"  "g43"  "g44"  "g45"  "g46"  "g47"  "g48"  "g49"  "g50"  "g51"  "g52"  "g53"  "g54"  "g55"  "g56"  "g57" 
# [58] "g58"  "g59"  "g60"  "g61"  "g62"  "g63"  "g64"  "g65"  "g66"  "g67"  "g68"  "g69"  "g70"  "g71"  "g72"  "g73"  "g74"  "g75"  "g76" 
# [77] "g77"  "g78"  "g79"  "g80"  "g81"  "g82"  "g83"  "g84"  "g85"  "g86"  "g87"  "g88"  "g89"  "g90"  "g91"  "g92"  "g93"  "g94"  "g95" 
# [96] "g96"  "g97"  "g98"  "g99"  "g100"

length(row.names(polys))

# [1] 100

class(polys)

# [1] "SpatialPolygons"
# attr(,"package")
# [1] "sp"

# assign projection to grid

proj4string(polys) = CRS("+proj=longlat +datum=NAD83 +no_defs +ellps=GRS80 +towgs84=0,0,0")

# create fake atttribute data for each grid cell

poly.data = data.frame(f=runif(length(row.names(polys)), 0, 14))
row.names(poly.data) <- paste0('g', 1:length(row.names(polys)))

# convert grid to a SpatialPolygonsDataFrame:

poly.df = SpatialPolygonsDataFrame(polys, poly.data)

# assign colors to grid cells

plotvar <- poly.df$f
nclr    <- 8
plotclr <- brewer.pal(nclr,"BuPu")

colcode <- ifelse((                plotvar <=   2), plotclr[1],
           ifelse((plotvar >   2 & plotvar <=   4), plotclr[2],
           ifelse((plotvar >   4 & plotvar <=   6), plotclr[3],
           ifelse((plotvar >   6 & plotvar <=   8), plotclr[4],
           ifelse((plotvar >   8 & plotvar <=  10), plotclr[5],
           ifelse((plotvar >  10 & plotvar <=  12), plotclr[6],
           ifelse((plotvar >  12 & plotvar <=  14), plotclr[7],
                                                    plotclr[8])))))))

jpeg(filename = "grid.plot.jpeg")

plot(poly.df, , col=colcode)
text(coordinates(poly.df), labels=row.names(poly.df))
dev.off()

enter image description here

Mark Miller
  • 12,483
  • 23
  • 78
  • 132