Search code examples
pythontopojsonjupyter-labaltairgeomap

How to create a TopoJSON geomap using Altair library for Python?


I am trying to create a geomap of a state using Altair package for Python. I will then plot let's say dots representing some event at a location specified by its latitude & longitude. I follow the Altair's example gallery here. The TopoJSON file is located in the GitHub repository deldersveld/topojson. However, I can't get it to draw the map of Michigan. Is this file missing something? Anyone who can help me?

Environment:

  • Windows 10
  • python 3
  • jupyter-lab 1.0.0a3
  • altair 3.0

Solution

  • You can do something like this:

    import altair as alt
    
    url = "https://raw.githubusercontent.com/deldersveld/topojson/master/countries/us-states/MI-26-michigan-counties.json"
    
    source = alt.topo_feature(url, "cb_2015_michigan_county_20m")
    
    alt.Chart(source).mark_geoshape().encode(
        tooltip='properties.NAME:N'
    )
    

    enter image description here

    The key is to look in the "objects" and "properties" entries of the TopoJSON file to figure out what to use for features and encodings.