from lets_plot import *
import pandas as pd
import requests
import json
from shapely.geometry import Point
from shapely.geometry import MultiPolygon, Polygon, LinearRing, Point, mapping
import geopandas as gpd
import fiona
LetsPlot.setup_html()
votes=dict(state=['California','Nevada','Utah', 'Arizona'],\
vote=['Clinton','Clinton','Trump','Trump'])
centroids = gpd.GeoDataFrame(
data={'key': ['California', 'Nevada', 'Utah', 'Arizona'],
'coord': [
Point(-119.99411, 37.27734),
Point(-116.66696, 38.50308),
Point(-111.54916, 39.49887),
Point(-111.66859, 34.16854)]},
geometry='coord')
centroids
def download_geometry(osm_id, key_value):
response = requests.get('http://polygons.openstreetmap.fr/get_geojson.py?id={0}¶ms=0'.format(osm_id))
with fiona.BytesCollection(bytes(str.encode(json.dumps(response.json()['geometries'][0])))) as f:
frame = gpd.GeoDataFrame.from_features(f, crs=f.crs)
# frame['geometry'] = frame.simplify(0.1)
frame['key'] = key_value
return frame
nv = download_geometry(165473, 'Nevada')
ca = download_geometry(165475, 'California')
ut = download_geometry(161993, 'Utah')
ar = download_geometry(162018, 'Arizona')
boundaries = ar
boundaries = pd.concat([boundaries, ca], ignore_index=True)
boundaries = pd.concat([boundaries, ut], ignore_index=True)
boundaries = pd.concat([boundaries, nv], ignore_index=True)
boundaries['geometry'] = boundaries.simplify(0.1)
boundaries
polygon = gpd.GeoDataFrame(
data={'key': ['Polygon'],
'coord': [Polygon(LinearRing([(-123, 34), (-120, 35), (-118, 32)]))]},
geometry='coord')
polygon
The data specified in the data and map parameters is merged by a key value from the map_id aesthetic.
ggplot() + geom_polygon(aes(fill='vote'), data = votes, map = boundaries, map_join=('state', 'key'), color='gray', alpha=0.4)
GeoDataFrame is supported natively in the data parameter. It works without map_id.
Geometries are automatically taken from GeoDataFrame.
p = ggplot()
p += geom_polygon(aes(fill='key'), boundaries, alpha=1) + scale_fill_hue(h = (0, 90))
p += geom_path(map=centroids, color='red', linetype=2, size =1)
p += geom_point(aes(fill='key'), data = centroids, color='gray', size = 10)
p += geom_rect(aes(fill='key'), polygon, color='gray', size=2)
p
ggplot() + geom_map(aes(fill='key'), boundaries, alpha=0.4) + geom_point(aes(color='vote'), votes, map=centroids, map_join=('state', 'key'), size=10)+ scale_fill_hue()