How to plot a specific column from a SpatialPolygonDataframe with leafletR? - r

I would like to create a choropleth map using leafletR::leaflet.
My data comes in a SpatialPolygonsDataFrame, and I would like to choose a specific column to be plotted.
With sp::spplot, this is easy-peasy, since the argument zcol allows me to specify the layer/column to be plotted:
library("maptools");library("sp");library("leafletR")
SP <- readShapePoly(system.file("shapes/sids.shp",
package="maptools")[1],
proj4string=CRS("+proj=longlat +datum=WGS84
+no_defs +ellps=WGS84
+towgs84=0,0,0"))
spplot(SP, zcol="BIR79")
However, with leafletR, I don't know how to specify the layer, and it just plots the plain map borders:
SP4leaflet <- toGeoJSON(data=SP, dest=tempdir(), name="BIR79")
SPleaflet <- leaflet(data=SP4leaflet, dest=tempdir(),
title="Trying to plot BIR79",
base.map="osm", popup="*")
SPleaflet
Any ideas on how to select the desired layer/column to be plotted with leafletR?

For the sake of completeness, I would like to mention that this is now easily possible using library(mapview).
library("maptools")
library("sp")
library("mapview")
SP <- readShapePoly(system.file("shapes/sids.shp",
package="maptools")[1],
proj4string=CRS("+proj=longlat +datum=WGS84
+no_defs +ellps=WGS84
+towgs84=0,0,0"))
spplot(SP, zcol="BIR79")
mapview(SP, zcol="BIR79")
See also http://edzer.github.io/sp/#interactive-maps-leaflet-mapview for a similar example and http://environmentalinformatics-marburg.github.io/web-presentations/20150723_mapView.html for more functionality of mapview.

Your code lacks a style definition. For a graduated style you have to create a style object using styleGrad. The prop parameter in styleGrad specifies the property you want to visualize.
library("maptools")
library("sp")
library("leafletR")
SP <- readShapePoly(system.file("shapes/sids.shp",
package="maptools")[1],
proj4string=CRS("+proj=longlat +datum=WGS84
+no_defs +ellps=WGS84
+towgs84=0,0,0"))
SP4leaflet <- toGeoJSON(data=SP, dest=tempdir(), name="BIR79")
SPleaflet <- leaflet(data=SP4leaflet, dest=tempdir(),
title="Trying to plot BIR79",
base.map="osm", popup="*")
## missing style definition
brks <- seq(0, max(SP$BIR79), by=5000)
clrs <- colorRampPalette(c("blue","yellow", "red"))(7)
stl <- styleGrad(prop="BIR79", breaks=brks, style.val=clrs,
out=1, leg="BIR79")
## end style definition
SPleaflet <- leaflet(data=SP4leaflet, dest=tempdir(),
title="Trying to plot BIR79", base.map="osm",
style=stl, popup="*")
SPleaflet

Maybe something like this works. Note that I used leaflet not leafletR. There is a good intro about the package here: here
library(leaflet)
library(maptools)
library(sp)
library(classInt)
library(classInt)
SP <- readShapePoly(system.file("shapes/sids.shp",
package="maptools")[1],
proj4string=CRS("+proj=longlat +datum=WGS84
+no_defs +ellps=WGS84
+towgs84=0,0,0"))
spplot(SP, zcol="BIR79")
## 6 classes with fixed given breaks
nclass <- classIntervals(SP$BIR79, n=6)
## Color for each class
colcode = findColours(nclass, c("red", "blue"))
leaflet(SP) %>% addTiles() %>% addPolygons(data = SP, color = colcode)

Related

Spatial polygons with messed up shape

I am new to spatial data. My goal is to get the gpx files from openstreetmap and plot polygons of Hungary's boundaries. I could successfully plot the boundaries under Járások but there are some boundaries under Kistérségek which are messed up, containing loops between points.
Image
Reproducable example for a specific boundary
library(XML)
library(magrittr)
library(sp)
parsed <- xmlParse("http://osmrm.openstreetmap.de/gpx.jsp?relation=1368104") %>% xmlToList()
coord <- do.call(rbind, parsed$rte)
name <- coord[1, 1]
coord <- coord[-(1:2), ]
coord <- apply(coord, 2, as.numeric)
poly <- Polygons(list(Polygon(coord)), name)
sp <- SpatialPolygons(list(poly), proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
plot(sp)
Result
Is the error because I missed something, or is it simply an issue with openstreetmap data? Any help is appreciated.

R Levelplot overlaying two SpatialPolygonsDataFrame on a RasterLayer projection

posted also on gis.stackexchange
I'm having some trouble plotting a RasterLayer and a SpatialPolygonsDataFrame in a level plot in R. Something is wrong with the projection, but I don't understand what.
Here you can find my
reproducible example data and code:
library(sp)
library(rgdal)
library(rgeos)
library(raster)
library(rasterVis)
library(maptools)
setwd("C:/...path_to/test2")
data<-read.csv("test.csv", header=TRUE)
#creating the raster from a data.frame and giving projection
raster<-rasterFromXYZ(data, crs="+proj=longlat")
raster_proj<-projectRaster(raster, crs="+proj=longlat +datum=WGS84
+ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs")
#loading shapes
nuts<-readShapePoly("NUTS_RG_WGS84.shp", proj4string=CRS("+proj=longlat"))
countries<-readShapePoly("countries.shp", proj4string=CRS("+proj=longlat"))
#subsetting the raster
raster_clip<- crop(raster_proj, countries, snap="near")
#plot
p.strip <- list(cex=1.5, lines=1, fontface='bold')
x.scale <- list(cex=1.5)
y.scale <- list(cex=1.5)
label <- list(labels=list(width=1, cex=1.5), height=0.95)
levelplot(raster_clip, par.settings = RdBuTheme, margin=FALSE,
at=seq(min(na.omit(values(raster_clip))), max(na.omit(values(raster_clip))), length.out=15),scales=list(x=x.scale, y=y.scale),
par.strip.text=p.strip, colorkey=label, xlab=list(label="Longitude", cex=2), ylab=list(label="Latitude", cex=2))+
layer(sp.polygons(nuts))+layer(sp.polygons(countries))
The error message is:
Error: Attempted to create layer with no geom.
But the raster and the polygons are in the same projection. I also tried to re-project the polygons using:
nuts <- spTransform(nuts, CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs"))
countries <- spTransform(countries, CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs"))
Any Idea?
If you don't want to or can't detach ggplot2 because you need it for something else, you can also call the layer function specifically from the latticeExtra package using:
levelplot(myRaster) +
latticeExtra::layer(sp.polygon(myPolygon))
detach("package:ggplot2", unload=TRUE)
I solved this problem by detaching ggplot2 from my library.

Gadm map with points layer in R

I have already asked about plotting points dependent on region, but now my question is about overlaying points given by coordinations over gadm map. I want to show different meteostations, using data based on this site or here is data used in code I've tried using such code:
require(ggplot2)
library(maptools)
library(rgdal)
library(RColorBrewer)
library(gpclib)
library(rgeos)
library(PBSmapping)
gpclibPermit()
rus<-load("C://RUS_adm1.RData")
proj4.str <- CRS("+init=epsg:3413 +lon_0=105")
gadm.prj <- spTransform(gadm, proj4.str)
rus<-gadm.prj
met <- read.csv2('C:\\meteo.txt')
cds <- data.frame(
Longitude=met$Long,
Latitude=met$Lat)
k<-as.matrix(cds)
popSP <- SpatialPointsDataFrame(coords=k,met["Elevation"], proj4string=proj4.str)
spplot(popSP, sp.layout=list('sp.polygons', gadm.prj))
, following advice from already mentioneed question, but it ends up with plotting points w/o gadm layer , I guess it's because of non-mentioning regions
Sorry, if question is dumb, but I will be grateful for any help
Here is the answer. Thanks to flowla
Edited code a little bit, I could plot different plot according to elevation.
library(rgdal)
library(raster)
rus <- load("C://RUS_adm1.RData")
popSP <- met <- read.csv2("C://meteo.txt")
for (i in c(3, 4))
popSP[, i] <- popSP[, i] / 1000
coordinates(popSP) <- ~ Long + Lat
projection(popSP) <- projection(gadm)
# Reprojection to EPSG:3413 (see http://www.spatialreference.org/ref/epsg/3413/)
proj4.str <- CRS("+proj=stere +lat_0=90 +lat_ts=70 +lon_0=105 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs")
gadm.prj <- spTransform(gadm, proj4.str)
popSP.prj <- spTransform(popSP, proj4.str)
col_no <- as.factor(as.numeric(cut(popSP.prj$Elevation,
c(0,2500,5000,10000,15000,20000,100000))))
levels(col_no) <- c("<2500", "2500-5000","5000-10000", "10000-15000","15000-20000",">20000" )
color = rainbow(6)
popSP.prj$col_no<-col_no
spplot(popSP.prj, "col_no", sp.layout=list('sp.polygons',cols="ID_0", gadm.prj), col.regions=color, main="Meteostations in Russia", key.space="right")

Map raw data and mean data based on the shapefile

sI have the dataset (pts) like this:
x <- seq(-124.25,length=115,by=0.5)
y <- seq(26.25,length=46,by=0.5)
z = 1:5290
longlat <- expand.grid(x = x, y = y) # Create an X,Y grid
pts=data.frame(longlat,z)
names(pts) <- c( "x","y","data")
I knew that I can map the dataframe (pts) into a map by doing:
library(sp)
library(rgdal)
library(raster)
library(maps)
coordinates(pts)=~x+y
proj4string(pts)=CRS("+init=epsg:4326") # set it to long, lat
pts = spTransform(pts,CRS(" +init=epsg:4326 +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"))
pts <- as(pts, "SpatialPixelsDataFrame")
r = raster(pts)
projection(r) = CRS(" +init=epsg:4326 +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0")
plot(r)
map("usa",add=T)
Now I would like to create a separate map which shows the means of pts across different regions. The shapefile I want to use is from ftp://ftp.epa.gov/wed/ecoregions/cec_na/NA_CEC_Eco_Level2.zip , however, this is a north america map. How can I create the map showing only US based on this north america map? Or is there another better way to do this? thanks so much.
I think that cutting out the non-US data based on the data in the shapefile alone would be hard, since the regions do not correspond to political boundaries - that could be done with rgeos though.
Assuming that "eco" is a SpatialPolygonsDataFrame read in by rgdal::readOGR or maptools::readShapeSpatial, see the available key data for indexing:
sapply(as.data.frame(eco), function(x) if(!is.numeric(x)) unique(x) else NULL)
If you just want to plot it, set up a map with only the US region to start with and then overplot.
library(maps)
map("usa", col = "transparent")
We see that the data is in Lambert Azimuthal Equal Area:
proj4string(eco)
[1] " +proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +a=6370997 +b=6370997 +units=m +no_defs"
So
require(rgdal)
eco.laea <- spTransform(eco, CRS("+proj=longlat +ellpse=WGS84"))
plot(eco.laea, add = TRUE)
If you want to plot in the original Lambert Azimuthal Equal Area you'll need to get the bounding box in that projection and start the plot based on that, I just used existing data to make an easy example. I'm pretty sure the data could also be cropped with rgeos against another boundary too, but depends what you actually want.

How to calculate polygon means and map them?

I have the dataset (pts) like this:
x <- seq(-124.25,length=115,by=0.5)
y <- seq(26.25,length=46,by=0.5)
z = 1:5290
longlat <- expand.grid(x = x, y = y) # Create an X,Y grid
pts=data.frame(longlat,z)
names(pts) <- c( "x","y","data")
I knew that I can map the dataframe (pts) into a map by doing:
library(sp)
library(rgdal)
library(raster)
library(maps)
coordinates(pts)=~x+y
proj4string(pts)=CRS("+init=epsg:4326") # set it to long, lat
pts = spTransform(pts,CRS(" +init=epsg:4326 +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"))
pts <- as(pts, "SpatialPixelsDataFrame")
r = raster(pts)
projection(r) = CRS(" +init=epsg:4326 +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0")
plot(r)
map("usa",add=T)
my question is that how I can calculate the means of the 10 EPA Regions and map the means?
the EPA regions can be found at the bottom of the webpage at
http://www.epa.gov/wed/pages/ecoregions/level_iii_iv.htm
Thanks
First read the shape file
er <- readOGR("Eco_Level_III_US.shp", "Eco_Level_III_US")
Then make sure ther raster r and the ecoregions er have the same projection
er.4326 <- spTransform(er, CRS("+init=epsg:4326 +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"))
Extract the r raster data from the shapefile (that may take a few minutes), calculate the mean and add it to your polyongs.
er.v <- extract(r, er.4326)
means <- sapply(er.v, mean)
er.4326$means <- means
And finally plot it
spplot(er.4326, "means")

Resources