diff --git a/r/2017-04-12-county-level-choropleth.Rmd b/r/2017-04-12-county-level-choropleth.Rmd deleted file mode 100644 index 76235e5f..00000000 --- a/r/2017-04-12-county-level-choropleth.Rmd +++ /dev/null @@ -1,153 +0,0 @@ ---- -description: How to create county-level choropleths in R with Plotly. -display_as: maps -language: r -layout: base -name: County Level Choropleth -order: 8 -output: - html_document: - keep_md: true -permalink: r/county-level-choropleth/ -thumbnail: thumbnail/county-level-choropleth.jpg ---- - -```{r, echo = FALSE, message=FALSE} -knitr::opts_chunk$set(message = FALSE, warning=FALSE) -``` -### Mapbox Access Token - -To plot on Mapbox maps with Plotly you *may* need a Mapbox account and a public [Mapbox Access Token](https://www.mapbox.com/studio). See our [Mapbox Mafig Layers](/r/mapbox-layers/) documentation for more information. If you're using a Chart Studio Enterprise server, please see additional instructions [here](https://help.plot.ly/mapbox-atlas). - -### Creating Polygon Boundaries - -```{r} -library(plotly) - -blank_layer <- list( - title = "", - showgrid = F, - showticklabels = F, - zeroline = F) - -fig <- map_data("county") -fig <- fig %>% filter(region == 'california') -fig <- fig %>% group_by(group) -fig <- fig %>% plot_ly( - x = ~long, - y = ~lat, - fillcolor = 'white', - hoverinfo = "none") -fig <- fig %>% add_polygons( - line = list(color = 'black', width = 0.5)) -fig <- fig %>% layout( - xaxis = blank_layer, - yaxis = blank_layer) - -fig -``` - -### Add County-Level Data - -```{r} -library(tidyverse) -library(plotly) - -df <- read.csv("https://raw.githubusercontent.com/bcdunbar/datasets/master/californiaPopulation.csv") - -cali <- map_data("county") -cali <- cali %>% filter(region == 'california') - -pop <- df -pop <- pop %>% group_by(County.Name) -pop <- pop %>% summarise(Pop = sum(Population)) - -pop$County.Name <- tolower(pop$County.Name) # matching string - -cali_pop <- merge(cali, pop, by.x = "subregion", by.y = "County.Name") - -cali_pop$pop_cat <- cut(cali_pop$Pop, breaks = c(seq(0, 11000000, by = 500000)), labels=1:22) - -fig <- cali_pop -fig <- fig %>% group_by(group) -fig <- fig %>% plot_ly(x = ~long, y = ~lat, color = ~pop_cat, colors = c('#ffeda0','#f03b20'), - text = ~subregion, hoverinfo = 'text') -fig <- fig %>% add_polygons(line = list(width = 0.4)) -fig <- fig %>% add_polygons( - fillcolor = 'transparent', - line = list(color = 'black', width = 0.5), - showlegend = FALSE, hoverinfo = 'none' - ) -fig <- fig %>% layout( - title = "California Population by County", - titlefont = list(size = 10), - xaxis = list(title = "", showgrid = FALSE, - zeroline = FALSE, showticklabels = FALSE), - yaxis = list(title = "", showgrid = FALSE, - zeroline = FALSE, showticklabels = FALSE) - ) - -fig -``` - -### Add Polygon to a Map Projection - -```{r} -library(plotly) - -geo <- list( - scope = 'usa', - showland = TRUE, - landcolor = toRGB("gray95"), - countrycolor = toRGB("gray80") -) - -fig <- cali_pop -fig <- fig %>% group_by(group) -fig <- fig %>% plot_geo( - x = ~long, y = ~lat, color = ~pop_cat, colors = c('#ffeda0','#f03b20'), - text = ~subregion, hoverinfo = 'text') -fig <- fig %>% add_polygons(line = list(width = 0.4)) -fig <- fig %>% add_polygons( - fillcolor = 'transparent', - line = list(color = 'black', width = 0.5), - showlegend = FALSE, hoverinfo = 'none' - ) -fig <- fig %>% layout( - title = "California Population by County", - geo = geo) - -fig -``` - -### Add Polygon to Mapbox -```{r} -library(plotly) - -mapboxToken <- paste(readLines("../.mapbox_token"), collapse="") # You need your own token -Sys.setenv("MAPBOX_TOKEN" = mapboxToken) # for Orca - -fig <- cali_pop -fig <- fig %>% group_by(group) -fig <- fig %>% plot_mapbox(x = ~long, y = ~lat, color = ~pop_cat, colors = c('#ffeda0','#f03b20'), - text = ~subregion, hoverinfo = 'text', showlegend = FALSE) -fig <- fig %>% add_polygons( - line = list(width = 0.4) - ) -fig <- fig %>% add_polygons(fillcolor = 'transparent', - line = list(color = 'black', width = 0.5), - showlegend = FALSE, hoverinfo = 'none' - ) -fig <- fig %>% layout( - xaxis = list(title = "", showgrid = FALSE, showticklabels = FALSE), - yaxis = list(title = "", showgrid = FALSE, showticklabels = FALSE), - mapbox = list( - style = 'light', - zoom = 4, - center = list(lat = ~median(lat), lon = ~median(long))), - margin = list(l = 0, r = 0, b = 0, t = 0, pad = 0) - ) -fig <- fig %>% config(mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN")) - -fig -``` \ No newline at end of file diff --git a/r/2020-01-30-choropleth-rmapbox.Rmd b/r/2020-01-30-choropleth-rmapbox.Rmd new file mode 100644 index 00000000..b2849e89 --- /dev/null +++ b/r/2020-01-30-choropleth-rmapbox.Rmd @@ -0,0 +1,132 @@ +--- +description: How to make a Mapbox Choropleth Map of US Counties in R with Plotly. +display_as: maps +language: r +layout: base +name: Choropleth mapbox +order: 8 +output: + html_document: + keep_md: true +page_type: u-guide +permalink: r/mapbox-county-choropleth/ +thumbnail: thumbnail/mapbox-choropleth.png +redirect_from: r/county-level-choropleth/ +--- + +```{r, echo = FALSE, message=FALSE} +knitr::opts_chunk$set(message = FALSE, warning=FALSE) +``` + +A [Choropleth Map](https://en.wikipedia.org/wiki/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](/r/choropleth-maps). + +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](https://www.mapbox.com/studio). See our [Mapbox Map Layers](/r/mapbox-layers/) documentation for more information. If you're using a Chart Studio Enterprise server, please see additional instructions [here](https://help.plot.ly/mapbox-atlas). + +### Introduction: main parameters for choropleth tile maps + +Making choropleth Mapbox maps requires two main types of input: + +1. GeoJSON-formatted geometry information where each feature has either an `id` field or some identifying value in `properties`. +2. A list of values indexed by feature identifier. + +The GeoJSON data is passed to the `geojson` argument, and the data is passed into the `color` argument of `px.choropleth_mapbox` (`z` if using `graph_objects`), in the same order as the IDs are passed into the `location` argument. + +**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](https://en.wikipedia.org/wiki/FIPS_county_code). + +```{r} +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 +``` + +### Data indexed by `id` + +Here we load unemployment data by county, also indexed by [FIPS code](https://en.wikipedia.org/wiki/FIPS_county_code). + +```{r} +df = read.csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv", header = T, colClasses = c("fips"="character")) +head(df) +``` +### Choropleth map using carto base map (no token needed) + +With `choroplethmapbox`, each row of the DataFrame is represented as a region of the choropleth. + +```{r} +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 Light base map: free token needed + +```{r} +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://plot.ly/r/reference/#scattermapbox](https://plot.ly/r/reference/#choroplethmapbox) for more information and options! \ No newline at end of file