Summary: This example shows how to create choropleth maps using Mapbox layers in F#.
Choropleth Maps display divided geographical areas or regions that are coloured, shaded or patterned in relation to a data variable. This provides a way to visualise values over a geographical area, which can show variation or patterns across the displayed location.
ChoroplethMapbox charts need GeoJSON formatted data.
GeoJSON is an open standard format designed for representing simple geographical features, along with their non-spatial attributes.
GeoJSON, or at least the type of GeoJSON accepted by plotly.js are
FeatureCollections. A feature has for example the
geometry field, which defines e.g. the corrdinates of it (think for example the coordinates of a polygon on the map)
properties field, a key-value pair of properties of the feature.
If you want to use GeoJSON with Plotly.NET (or any plotly flavor really), you have to know the property of the feature you are mapping your data to. In the following example this is simply the
id of a feature, but you can access any property by
Consider the following GeoJSON:
// we are using the awesome FSharp.Data project here to perform a http request #r "nuget: FSharp.Data" open FSharp.Data open Newtonsoft.Json let geoJson = Http.RequestString "https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json" |> JsonConvert.DeserializeObject // the easiest way to use the GeoJSON object is deserializing the JSON string.
it looks like this:
It basically contains all US counties as polygons on the map. Note that the
id property corresponds to the fips code.
To visualize some data using these counties as locations on a choropleth map, we need some exmaple data:
// we use the awesome Deedle data frame library to parse and extract our location and z data #r "nuget: Deedle" open Deedle 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")
The data looks like this:
As the data contains the fips code and associated unemployment data, we can use the fips codes as locations and the unemployment as z data:
let locations: string  = data |> Frame.getCol "fips" |> Series.values |> Array.ofSeq let z: int  = data |> Frame.getCol "unemp" |> Series.values |> Array.ofSeq
And finally put together the chart using GeoJSON:
open Plotly.NET open Plotly.NET.LayoutObjects let choroplethMapbox = Chart.ChoroplethMapbox( locations = locations, z = z, geoJson = geoJson, FeatureIdKey="id" ) |> Chart.withMapbox( Mapbox.init( Style=StyleParam.MapboxStyle.OpenStreetMap, // Use the free open street map base map layer Center=(-104.6,50.45) ) )