Mapbox Choropleth Maps in R
How to make a Mapbox Choropleth Map of US Counties in R with Plotly.
New to Plotly?
Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.
A Choropleth Map is a map composed of colored polygons. It is used to represent spatial variations of a quantity. This page documents how to build tile-map choropleth maps, but you can also build outline choropleth maps using our non-Mapbox trace types.
Below we show how to create Choropleth Maps using Plotly Choroplethmapbox
graph object.
Mapbox Access Token and Base Map Configuration
To plot on Mapbox maps with Plotly you may need a Mapbox account and a public Mapbox Access Token. See our Mapbox Map Layers documentation for more information. If you're using a Chart Studio Enterprise server, please see additional instructions here.
Introduction: main parameters for choropleth tile maps
Making choropleth Mapbox maps requires two main types of input:
- GeoJSON-formatted geometry information where each feature has either an
id
field or some identifying value inproperties
. - A list of values indexed by feature identifier.
The GeoJSON data is passed to the geojson
argument, and the data is passed into the z
argument of plot_geo
.
Note the geojson
attribute can also be the URL to a GeoJSON file, which can speed up map rendering in certain cases.
GeoJSON with feature.id
Here we load a GeoJSON file containing the geometry information for US counties, where feature.id
is a FIPS code.
library(rjson)
url = 'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json'
json_file <- rjson::fromJSON(file=url)
json_file$features[[1]]$id
## [1] "01001"
Data indexed by id
Here we load unemployment data by county, also indexed by FIPS code.
df = read.csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv", header = T, colClasses = c("fips"="character"))
head(df)
## fips unemp
## 1 01001 5.3
## 2 01003 5.4
## 3 01005 8.6
## 4 01007 6.6
## 5 01009 5.5
## 6 01011 7.2
Mapbox Choropleth Map Using GeoJSON
With choroplethmapbox
, each row of the DataFrame is represented as a region of the choropleth.
library(rjson)
library(plotly)
url <- 'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json'
counties <- rjson::fromJSON(file=url)
url2<- "https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv"
df <- read.csv(url2, colClasses=c(fips="character"))
fig <- plot_ly()
fig <- fig %>% add_trace(
type="choroplethmapbox",
geojson=counties,
locations=df$fips,
z=df$unemp,
colorscale="Viridis",
zmin=0,
zmax=12,
marker=list(line=list(
width=0),
opacity=0.5
)
)
fig <- fig %>% layout(
mapbox=list(
style="carto-positron",
zoom =2,
center=list(lon= -95.71, lat=37.09))
)
fig
Mapbox Choropleth Map Using GeoJSON with featureidkey
If the GeoJSON you are using either does not have an id
field or you wish you use one of the keys in the properties
field, you may use the featureidkey
parameter to specify where to match the values of locations.
In the following GeoJSON object/data-file pairing, the values of properties.district
match the values of the district
column:
library(plotly)
library(rjson)
url <- 'https://raw.githubusercontent.com/plotly/datasets/master/election.geojson'
geojson <- rjson::fromJSON(file=url)
url2<- "https://raw.githubusercontent.com/plotly/datasets/master/election.csv"
df <- read.csv(url2)
g <- list(
fitbounds = "locations",
visible = FALSE
)
fig <- plot_ly()
fig <- fig %>% add_trace(
type="choroplethmapbox",
geojson=geojson,
locations=df$district,
z=df$Bergeron,
colorscale="Viridis",
featureidkey="properties.district"
)
fig <- fig %>% colorbar(title = "Bergeron Votes")
fig <- fig %>% layout(
mapbox=list(
style="carto-positron",
zoom =9,
center=list(lon=-73.7073, lat=45.5517))
)
fig
Mapbox Light base map: free token needed
library(rjson)
library(plotly)
mapboxToken <- paste(readLines("../.mapbox_token"), collapse="") # You need your own token
Sys.setenv("MAPBOX_TOKEN" = mapboxToken) # for Orca
url <- 'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json'
counties <- rjson::fromJSON(file = url)
url2<- "https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv"
df <- read.csv(url2,colClasses = c(fips = "character"))
fig <- plot_ly()
fig <- fig %>% add_trace(
type = "choroplethmapbox",
geojson = counties,
locations = df$fips,
z=df$unemp,
colorscale="Viridis",
zmin=0,
zmax=12,
marker=list(line = list(
width = 0),
opacity=0.5
)
)
fig <- fig %>% layout(
mapbox = list(
style = "light",
zoom =3,
center = list(lon = -95.7129, lat = 37.0902))
)
fig <- fig %>% config(mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN"))
fig
Reference
See https://plotly.com/r/reference/#scattermapbox for more information and options!
What About Dash?
Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.
Learn about how to install Dash for R at https://dashr.plot.ly/installation.
Everywhere in this page that you see fig
, you can display the same figure in a Dash for R application by passing it to the figure
argument of the Graph
component from the built-in dashCoreComponents
package like this:
library(plotly)
fig <- plot_ly()
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... )
library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)
app <- Dash$new()
app$layout(
htmlDiv(
list(
dccGraph(figure=fig)
)
)
)
app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE)