Mapbox Choropleth Maps in F#
How to make a Mapbox Choropleth Map of US Counties in F# with Plotly.
#r "nuget: Plotly.NET,2.0.0-preview.8"
#r "nuget: Plotly.NET.Interactive,2.0.0-preview.8"
#r "nuget: FSharp.Data"
#r "nuget:Deedle"
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.
Mapbox Access Tokens and Base Map Configuration¶
To plot on Mapbox maps with Plotly you may need a Mapbox account and a public Mapbox Access Token
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 in properties. A list of values indexed by feature identifier.
GeoJSON with feature.id¶
Here we load a GeoJSON file containing the geometry information for US counties, where feature.id is a FIPS code.
open FSharp.Data
type jsonProvider = JsonProvider<"https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json">
let counties = jsonProvider.Load("https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json")
counties.Features.[0].Id
Data indexed by id¶
Here we load unemployment data by county, also indexed by FIPS code.
open Deedle
open FSharp.Data
let data =
Http.RequestString "https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv"
|> fun csv -> Frame.ReadCsvString(csv,true,separators=",",schema="fips=string,unemp=float")
let getColumnData col=
data
|> Frame.getCol col
|> Series.values
|> Array.ofSeq
let fips:string[] = getColumnData "fips" |> Array.take 5
let unemp:float[] = getColumnData "unemp" |> Array.take 5
Array.zip fips unemp
Mapbox Choropleth Map Using GeoJSON¶
With choroplethmapbox, each row of the DataFrame is represented as a region of the choropleth.
open Plotly.NET
open Newtonsoft.Json
open FSharp.Data
open Deedle
open Plotly.NET.LayoutObjects
let data =
Http.RequestString "https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv"
|> fun csv -> Frame.ReadCsvString(csv,true,separators=",",schema="fips=string,unemp=float")
let geoJson =
Http.RequestString "https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json"
|> JsonConvert.DeserializeObject
let locations: string [] =
data
|> Frame.getCol "fips"
|> Series.values
|> Array.ofSeq
let z: int [] =
data
|> Frame.getCol "unemp"
|> Series.values
|> Array.ofSeq
Chart.ChoroplethMapbox(z=z,geoJson=geoJson,locations=locations,FeatureIdKey="id",Colorscale=StyleParam.Colorscale.Viridis,ZMin=0.,ZMax=12.)
|> Chart.withMapbox(
Mapbox.init(Style=StyleParam.MapboxStyle.CartoPositron,Zoom=3.,Center=(-95.7129,37.0902))
)