Choropleth Maps in F#

How to make choropleth maps in F# with Plotly.


In [1]:
#r "nuget: Plotly.NET,  2.0.0-preview.8"
#r "nuget: Plotly.NET.Interactive,  2.0.0-preview.8"
Installed Packages
  • Plotly.NET, 2.0.0-preview.8
  • Plotly.NET.Interactive, 2.0.0-preview.8

Loading extensions from Plotly.NET.Interactive.dll

Added Kernel Extension including formatters for Plotly.NET charts.

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 outline choropleth maps, but you can also build choropleth tile maps using our Mapbox trace types.

Base Map Configuration

Introduction: main parameters for choropleth outline maps

Making choropleth maps requires two main types of input:

Geometry information: This can either be a supplied GeoJSON file where each feature has either an id field or some identifying value in properties; or one of the built-in geometries within plot_ly: US states and world countries (see below) 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 choropleth traces.

Note the geojson attribute can also be the URL to a GeoJSON file, which can speed up map rendering in certain cases.

Choropleth Map Using GeoJSON

In [2]:
#r "nuget: FSharp.Data"
#r "nuget: Newtonsoft.Json"
open FSharp.Data
open Newtonsoft.Json
open Plotly.NET.LayoutObjects
open Plotly.NET.TraceObjects
    
#r "nuget: Deedle"
open Deedle
open System.IO
open System.Text

open Plotly.NET 

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 locationsGeoJSON: string [] = 
    data
    |> Frame.getCol "fips"
    |> Series.values
    |> Array.ofSeq
let zGeoJSON: int [] = 
    data
    |> Frame.getCol "unemp"
    |> Series.values
    |> Array.ofSeq

Chart.ChoroplethMap(
    locations = locationsGeoJSON,
    z = zGeoJSON,
    Locationmode=StyleParam.LocationFormat.GeoJson_Id,
    GeoJson = geoJson,
    FeatureIdKey="id"
)

|> Chart.withGeo(
    Geo.init(
        Scope=StyleParam.GeoScope.NorthAmerica, 
        Projection=GeoProjection.init(StyleParam.GeoProjectionType.AzimuthalEqualArea),
        ShowLand=true,
        
        LandColor = Color.fromString "lightgrey"
    )
)

|> Chart.withSize (800.,800.)
Installed Packages
  • Deedle, 2.4.3
  • FSharp.Data, 4.2.4
  • newtonsoft.json, 12.0.3
Out[2]: