I have seen an interactive choropleth map at the US county level at www.betydb.org. I would like to reproduce a similar map using R. I just want the map and the tooltips (no
This is a question coming from 2013. I am not sure if the leaflet
package was out back then. It is the end of 2017 now, and it is possible to achieve your task. I want to leave the following for you, if you still need to do similar tasks. In this case, there are some missing counties in the data set. These counties exsit in the USA polygon data, but they are missing in mydata
. So I added these counties to mydata
using setdiff()
and bind_rows()
. When you draw a leaflet map, you need to specify your color palette. Avg_yield
is a continuous variable. So you use colorNumeric()
. I leave a screen shot showing a part of the leaflet map.
library(raster)
library(leaflet)
library(tidyverse)
# Get USA polygon data
USA <- getData("GADM", country = "usa", level = 2)
### Get data
mydata <- read.csv("https://www.betydb.org/miscanthus_county_avg_yield.csv",
stringsAsFactors = FALSE) %>%
dplyr::select(COUNTY_NAME, Avg_yield)
### Check counties that exist in USA, but not in mydata
### Create a dummy data frame and bind it with mydata
mydata <- data.frame(COUNTY_NAME = setdiff(USA$NAME_2, mydata$COUNTY_NAME),
Avg_yield = NA,
stringsAsFactors = FALSE) %>%
bind_rows(mydata)
### Create a color palette
mypal <- colorNumeric(palette = "viridis", domain = mydata$Avg_yield)
leaflet() %>%
addProviderTiles("OpenStreetMap.Mapnik") %>%
setView(lat = 39.8283, lng = -98.5795, zoom = 4) %>%
addPolygons(data = USA, stroke = FALSE, smoothFactor = 0.2, fillOpacity = 0.3,
fillColor = ~mypal(mydata$Avg_yield),
popup = paste("Region: ", USA$NAME_2, "<br>",
"Avg_yield: ", mydata$Avg_yield, "<br>")) %>%
addLegend(position = "bottomleft", pal = mypal, values = mydata$Avg_yield,
title = "Avg_yield",
opacity = 1)