#!/usr/bin/env python # coding: utf-8 # # Map # In[5]: import fiona #This is a canned demo - I happen to have the Local Authority Code for the Isle of Wight... #...and copies of ward geojson files by LA from https://github.com/martinjc/UK-GeoJSON geojson_local='IWgeodata/wards_by_lad/E06000046.json' fi=fiona.open(geojson_local) centre_lat,centre_lon=((fi.bounds[0]+fi.bounds[2])/2,(fi.bounds[1]+fi.bounds[3])/2) # In[6]: import json with open(geojson_local) as f: jdata = json.load(f) for j in jdata['features']: print(j['properties']['WD13CD'],j['properties']['WD13NM']) # In[7]: import pandas as pd # In[8]: #previous results from https://blog.ouseful.info/2013/05/15/asking-questions-of-data-contained-in-a-google-spreadsheet-using-a-basic-structured-query-language/ url="https://docs.google.com/spreadsheets/d/1oyoF9Tgc2n0q2YksNACVf2AY4crOnJIhndTXyEoTJmQ/export?format=csv" df=pd.read_csv("https://docs.google.com/spreadsheets/d/1oyoF9Tgc2n0q2YksNACVf2AY4crOnJIhndTXyEoTJmQ/export?format=csv") df.head(10) # In[9]: #Compare the official ward names with ones in result file set(df['Electoral Division'].unique()) - set(j['properties']['WD13NM'] for j in jdata['features']),set(j['properties']['WD13NM'] for j in jdata['features']) - set(df['Electoral Division'].unique()) # In[10]: #Clean the previous results data df['Electoral Division']=df['Electoral Division'].str.replace('&','and') df['Electoral Division'].unique() # In[11]: #Find winning percentages winners=df[ ~df['Candidate'].isin(['Total votes cast', 'Postal votes', 'Postal votes'])].sort_values('Electorate', ascending=False).groupby('Electoral Division', as_index=False).first() winners['pc']=100*winners['Electorate']/winners['NoOnRoll'] winners # In[29]: #Percentage of no on roll voting for winner #crib? https://blog.ouseful.info/2015/04/17/creating-interactive-election-maps-using-folium-and-ipython-notebooks/ #http://nbviewer.jupyter.org/gist/psychemedia/fbcd7cf1daabe0004e27/folium_shapefiles.ipynb import folium iwmap=folium.Map([centre_lon,centre_lat], zoom_start=11) iwmap.choropleth( geo_path=geojson_local, data=winners, columns=['Electoral Division', 'pc'], key_on='feature.properties.WD13NM', fill_color='PuBuGn', fill_opacity=0.7 ) iwmap # In[37]: turnout=df[df['Candidate'].isin(['Total votes cast'])][['Electoral Division','Candidate','Electorate','NoOnRoll']] turnout['turnout']=turnout['Electorate']/turnout['NoOnRoll'] turnout # In[38]: #Percentage of no on roll voting #crib? https://blog.ouseful.info/2015/04/17/creating-interactive-election-maps-using-folium-and-ipython-notebooks/ #http://nbviewer.jupyter.org/gist/psychemedia/fbcd7cf1daabe0004e27/folium_shapefiles.ipynb import folium iwmap=folium.Map([centre_lon,centre_lat], zoom_start=11) iwmap.choropleth( geo_path=geojson_local, data=turnout, columns=['Electoral Division', 'turnout'], key_on='feature.properties.WD13NM', fill_color='PuBuGn', fill_opacity=0.7 ) iwmap # In[12]: winners['Party'].unique() # In[13]: colmap={'Island Independents':'lightblue', 'Conservative':'blue', 'Independent':'black', 'Labour':'red', 'none':'grey', 'Sandown Independents':'darkgrey', 'UKIP':'purple'} # In[15]: winners['col']=winners['Party'].map(colmap) winners.head() # In[25]: #Ward by Party #There has to be an easier way of doing qualitative choropleths using folium #This hack is one I struggled towards finding before... #http://nbviewer.jupyter.org/gist/psychemedia/fbcd7cf1daabe0004e27/folium_shapefiles.ipynb jj=json.load(open(geojson_local)) results_map = folium.Map([centre_lon,centre_lat], zoom_start=11) for c in jj['features']: #The choropleth format requires that features are provided in a list and a FeatureCollection defined as the type #So we wrap the feature definition for each constituency in the necessary format geodata= {"type": "FeatureCollection", "features": [c]} #Get the name of the seat for the current constituency ward=c['properties']['WD13NM'] #We can now lookup the colour colour= colmap[winners[winners['Electoral Division']==ward]['Party'].iloc[0]] results_map.choropleth(geo_str= json.dumps(geodata),fill_color=colour,fill_opacity=1) results_map # In[ ]: # In[ ]: