Skip to content

Instantly share code, notes, and snippets.

@2torus
Created May 15, 2022 15:02
Show Gist options
  • Select an option

  • Save 2torus/6919dd27a9ec45af17108de51df56dc3 to your computer and use it in GitHub Desktop.

Select an option

Save 2torus/6919dd27a9ec45af17108de51df56dc3 to your computer and use it in GitHub Desktop.
Plot US states outlines in Bokeh
import json
from bokeh.io import output_notebook
from bokeh.plotting import figure, show, ColumnDataSource
from bokeh.models import GeoJSONDataSource
output_notebook()
# If you don't have the file yet
import requests as rq
# Also possible
# https://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_040_00_500k.json
# https://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_040_00_20m.json
# 500k is actually more detailed
rs = rq.get('https://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_040_00_5m.json')
geo_json = rs.json()
# We will cheat and move the part of Alaska in the Eastern Hemisphere to the left Western Hemishpere
# Skip this if not drawing Alaska or don't want to "cheat"
def move_to_western(feature):
"""
feature is an array {'properties': {'NAME': ...}, 'geometry': {..., 'coordinates': [[[[x_i, y_i]]]] }}
"""
geometry = feature['geometry']
coordinates = geometry['coordinates']
def move_left(coord):
return [-360 + coord[0] if coord[0] > 0 else coord[0], coord[1]]
def rec_move_left(lst):
if len(lst) > 0:
if not isinstance(lst[0], list):
return move_left(lst)
return [rec_move_left(item) for item in lst]
return lst
new_coordinates = rec_move_left(coordinates)
# instead of proper deepcopy
new_geometry = dict(geometry)
new_geometry['coordinates'] = new_coordinates
new_feature = dict(feature)
new_feature['geometry'] = new_geometry
return new_feature
def move_ak_to_western(feature):
if feature['properties']['NAME'] == 'Alaska':
return move_to_western(feature)
return feature
new_geo_json = dict(geo_json)
new_geo_json['features'] = [move_ak_to_western(feature) for feature in features]
geo_source = GeoJSONDataSource(geojson=json.dumps(new_geo_json))
p = figure()
p.multi_line('xs', 'ys', source=geo_source, color='gray', line_width=1.5)
show(p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment