step one: import data
library(maps)
library(leaflet)
library(dplyr)
##
## Attaching package: 'dplyr'
##
## The following objects are masked from 'package:stats':
##
## filter, lag
##
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
data(countyMapEnv) #load maps package data
#load dummy data
dummyData <- read.csv("./DummyData.csv")
#show summary of dummyData
summary(dummyData)
## ID RespDate County CertStatus
## Min. : 1.0 11/18/16: 8 Alameda : 21 Min. :0.000
## 1st Qu.:100.8 10/27/16: 6 Los Angeles : 21 1st Qu.:0.000
## Median :200.5 10/13/16: 5 Riverside : 21 Median :0.000
## Mean :200.5 10/20/16: 5 Sacramento : 21 Mean :0.455
## 3rd Qu.:300.2 11/12/16: 5 San Diego : 21 3rd Qu.:1.000
## Max. :400.0 11/5/16 : 5 San Francisco: 21 Max. :1.000
## (Other) :366 (Other) :274
#summarize by County
sumByCounty <- tapply(dummyData$ID, dummyData$County, length)
sumByCounty <- as.data.frame(sumByCounty)
sumByCounty$NAME <- row.names(sumByCounty)
making the map in leaflet
#Here is an example of a leaflet map
library(rgdal)
## Loading required package: sp
## rgdal: version: 1.0-4, (SVN revision 548)
## Geospatial Data Abstraction Library extensions to R successfully loaded
## Loaded GDAL runtime: GDAL 1.11.2, released 2015/02/10
## Path to GDAL shared files: /Library/Frameworks/R.framework/Versions/3.2/Resources/library/rgdal/gdal
## Loaded PROJ.4 runtime: Rel. 4.9.1, 04 March 2015, [PJ_VERSION: 491]
## Path to PROJ.4 shared files: /Library/Frameworks/R.framework/Versions/3.2/Resources/library/rgdal/proj
## Linking to sp version: 1.1-1
#loading shapefile
counties <- readOGR("./shapefiles", layer="cb_2014_us_county_20m")
## OGR data source with driver: ESRI Shapefile
## Source: "./shapefiles", layer: "cb_2014_us_county_20m"
## with 3220 features
## It has 9 fields
## Warning in readOGR("./shapefiles", layer = "cb_2014_us_county_20m"): Z-
## dimension discarded
#filtering for only california
counties <- subset(counties, counties@data$STATEFP=="06")
#making a leaflet map of california counties!
leaflet() %>% addTiles() %>% addPolygons(data=counties)
#merging in your data into this shapefile
counties@data = data.frame(counties@data, sumByCounty[match(counties@data[,"NAME"], sumByCounty[,"NAME"]),])
#set color palette
colorRamp <- colorRamp(c("#eb4f3f","#e9db4f","#56e460"), interpolate="spline")
palette <- colorNumeric(colorRamp, counties@data$sumByCounty)
leaflet() %>% addProviderTiles("CartoDB.Positron") %>%
addPolygons(
weight=2,
opacity = 0.8,
data=counties,
color = ~palette(sumByCounty),
popup = ~paste("<strong>County:</strong>",NAME,
"<br>",
"<strong>Count:</strong>",sumByCounty)
) %>% addLegend(title = "Counts by county", pal = palette, values = counties@data$sumByCounty, opacity = 0.9, position="bottomleft")