Skip to content

Instantly share code, notes, and snippets.

@kot-behemoth
Last active April 9, 2019 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kot-behemoth/01949f8e9a94d9d343bd62e45adb41a1 to your computer and use it in GitHub Desktop.
Save kot-behemoth/01949f8e9a94d9d343bd62e45adb41a1 to your computer and use it in GitHub Desktop.
Blog: "Zooming in" on a map in Altair

"Zooming in" on a map in Altair

Altair doesn't allow making maps (aka mark_geoshape) interactive, since geo markers do not yet support interaction in Vega-Lite (vega/vega-lite#3306).

I stumbled upon this problem when I needed to only display information in only one US state, but the official example shows the full map of the US. Furthermore, it's not possible to set a fixed zoom, so that only one state is visible when the map is shown.

I found a solution by essentially only displaying the state I need, instead of the whole map. For that, I had to find the relevant geometry file. I found a GeoJson file for the state I was interested in from world.geo.json repo (state files are located here, below the folders). Then, I loaded it into Geojson.io geojson.io, and exported as TopoJson (I'm sure it could be done via better means, but this was the quickest). Finally, I simply used the local file in my notebook as such:

state = alt.topo_feature('./map.topojson', 'collection')

(
    alt.Chart(state)
    .mark_geoshape(
        fill='white',
        stroke='black'
    )
    .project(type='albersUsa')
)

Note that the second argument to alt.topo_feature can be found in the topojson file like this:

{
  "type": "Topology",
  "objects": {
    "collection": {     <--------- this is the argument
      "type": "GeometryCollection",
      "geometries": [
        {
          "type": "Polygon",
          "id": "USA-TX",
          "properties": {
            "fips": 48,
            "name": "Texas"
          },
          ...

Hope this helps while vega-lite gets the required functionality!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment