R Plot Filled Longitude-Latitude Grid Cells on Map

geospatial, ggplot2, plot, r

Solution

An alternative to using either `spplot` or `image` is to use `ggplot2`. The relevant geometries are `geom_raster` and `geom_tile`. The first is supposed to perform better and yield smaller files, and the second is more standard. The following example call:

ggplot(aes(x = x, y = y, fill = value), data = dat_grid) + geom_tile() + 
  geom_path(data = ant_ggplot)

orginates from this blogpost of mine. In addition, `ggplot2` supports a range of projections through the `mapproj` package, see `coord_map` for more details.

The following is a working example (provided you've defined `YOUR_DATA` to have x,y,z columns):

library(ggplot2)
library(maps)
us_states <- map_data("state")
(ggplot(aes(x=x,y=y,fill=z),data=YOUR_DATA) + geom_tile())+geom_polygon(data=us_states,aes(x=long, y=lat, group=group), colour="black", fill="white", alpha=0)

Problem

I have a data frame containing a number of `(x,y,z)` data points, `(x,y)` is the lower-right coordinate of a longitude-latitude cell of size `w` (e.g. a 1-degree grid). The `z` value has been averaged over this cell. I'd like to plot these points in R so that the entire grid cell is filled with some colour derived from `z`. The result would look something like one of these images: The projection itself (e.g. Lambert conformal conic, equirectangular) isn't important, just the grid cell plotting. My data is sparse: not every longitude-latitude cell will have data associated with it. My hope would be a solution similar to ``` library(maps) map("state") grid_points(my_data,c("x","y","z"),0.5) ``` where 0.5 is the grid resolution above, indicating a 0.5-degree cell. Any thoughts? Thanks!

Original source