#!/usr/bin/env python # coding: utf-8 # In[1]: 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 # In[2]: LetsPlot.setup_html() # In[3]: votes=dict(state=['California','Nevada','Utah', 'Arizona'],\ vote=['Clinton','Clinton','Trump','Trump']) # In[4]: 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 # In[5]: 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 # In[6]: nv = download_geometry(165473, 'Nevada') ca = download_geometry(165475, 'California') ut = download_geometry(161993, 'Utah') ar = download_geometry(162018, 'Arizona') # In[7]: 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 # In[8]: polygon = gpd.GeoDataFrame( data={'key': ['Polygon'], 'coord': [Polygon(LinearRing([(-123, 34), (-120, 35), (-118, 32)]))]}, geometry='coord') polygon # ### GeoDataFrame in the map parameter using map_id # The data specified in the *data* and *map* parameters is merged by a key value from the *map_id* aesthetic. # In[9]: ggplot() + geom_polygon(aes(fill='vote'), data = votes, map = boundaries, map_join=('state', 'key'), color='gray', alpha=0.4) # ### GeoDataFrame in data parameter # GeoDataFrame is supported natively in the *data* parameter. It works without *map_id.* # Geometries are automatically taken from GeoDataFrame. # In[10]: 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 # #### Combining layers from the data and map parameters # In[ ]: 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() # In[ ]: