Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting shp file in leaflet, works in ggplot

I'm stumped getting my dataframe to plot in leaflet. I have one shapefile and one csv that I merged together. The resulting dataframe has several columns, including long, lat, and "percent".

I am able to plot this using ggplot with the following code:

p <- ggplot() +
    geom_polygon(data = nyc_plotData, aes(x=long, y=lat, group = group, 
                                      fill=percent)) +
    geom_polygon(data = county, aes(x=long, y=lat, group = group), 
                                      fill=NA, color = "black", size = 0.25) +
    coord_map(xlim = c(-74.26, -73.71), ylim = c(40.49,40.92))

The result is a choropleth map of income distribution in nyc:

nyc plot

When I try to use the same dataframe in leaflet, I get this error:

Don't know how to get path data from object of class data.frame

I understand I have to reformat my dataframe. I tried various ways to convert to a SpatialPolygonDataFrame. For example:

xy <- nyc_plotData[,c(1,2)]
spdf <- SpatialPolygonsDataFrame(coords = xy, data = nyc_plotData,
                               proj4string = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"))

gives the following error:

Error in SpatialPolygonsDataFrame(coords = xy, data = nyc_plotData, proj4string = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")) : unused arguments (coords = xy, proj4string = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"))

I'm clearly missing something, but I haven't been able to find any examples of this problem anywhere online.

I'd really appreciate any tips or advice dealing with shapefiles and plotting in leaflet.

like image 530
Claire Avatar asked Oct 12 '15 15:10

Claire


1 Answers

As the others point out (and you note) you'll need to convert to a SpatialPolygonsDataFrame. In order to do this I think you'd need to convert each tract to a Polygon, then Polygons, then SpatialPolygons and finally a SpatialPolygonsDataFrame. There is code below for this.

An alternative: You started with a SpatialPolygonsDataFrame and then used fortify to map with ggplot2. You could go back to the original SpatialPolygonsDataFrame and merge the data slot with your tabular census data (being careful not to change the row order).

I put more detail on both options here.

library(dplyr)
library(sp)

polyFunc<-function(groupname, dat){
  poly<-filter(dat, id==groupname) %>% 
    select(long, lat)
  return(Polygons(list(Polygon(poly)), groupname))
}


tracts <- distinct(ggtract, id, percent)
tractname <- tracts$id
polygons<-lapply(tractname, function(x) polyFunc(x, dat=ggtract)) 
sp.polygon<-SpatialPolygons(polygons)
df.polygon<-SpatialPolygonsDataFrame(sp.polygon, 
                                     data=data.frame(row.names=tractname, tracts))
like image 86
ZRoss Avatar answered Oct 15 '22 19:10

ZRoss