def map_generator(map_data,key,title): ### This function makes a colored map for the data given, white outlines for countries without data geo_data = [{'name': 'countries', 'url': 'world-countries.topo.json', 'feature': 'world-countries'}, {'name': 'countries_outline', 'url': 'world-countries.topo.json', 'feature': 'world-countries'} ] mapx = vincent.Map(data=map_data, geo_data=geo_data, projection='mercator', scale=150, data_bind=key, data_key='iso3', map_key={'countries': 'id'}, brew='Purples') del mapx.marks[1].properties.update mapx.marks[1].properties.enter.stroke.value = '#000' mapx.legend(title=title) return mapx
def visualizePandasData(stateData, thresholds, file_name, color_option): state_topo = 'https://raw.githubusercontent.com/wrobstory/vincent_map_data/master/us_states.topo.json' geo_data = [{ 'name': 'states', 'url': state_topo, 'feature': 'us_states.geo' }] vis = vincent.Map(data=stateData, geo_data=geo_data, scale=1000, projection='albersUsa', data_bind=MappingHandlerKeys.DATA_BIND_KEY, data_key=MappingHandlerKeys.DATA_KEY, map_key={'states': 'properties.NAME'}, brew=color_option) vis.scales[0].type = 'threshold' vis.scales[0].domain = thresholds vis.legend(title=MappingHandlerKeys.MAP_TITLE_KEY) vis.to_json(file_name)
import pickle, vincent import pandas as pd with open('db.p', 'rb') as f: df = pickle.load(f) world_topo = r'world-countries.topo.json' geo_data = [{ 'name': 'countries', 'url': world_topo, 'feature': 'world-countries' }] vis = vincent.Map(geo_data=geo_data, scale=200)
if(count < num_projects): pbar.update(count) else: to_add = num_projects - (count - 50) pbar.update(to_add) pbar.finish() geo_data = [{'name': 'countries', 'url': 'https://raw.githubusercontent.com/wrobstory/vincent_map_data/master/world-countries.topo.json', 'feature': 'world-countries'}] country_dict[donating_org] = addNonDonatedCountries(country_dict[donating_org], get_id) receiving_df = pd.DataFrame(list(country_dict[donating_org].iteritems()), columns=['iso_a3', 'total_received']) merged = pd.merge(receiving_df, country_df, on='iso_a3', how='inner') # Uses vincent to create a map in vega format vis = vincent.Map(data=merged, geo_data=geo_data, scale=1000, projection='patterson', data_bind='total_received', data_key='iso_a3', map_key={'countries': 'id'}) vis.legend(title="Donation Amount") json_file_name = donating_org.replace(' ', '_') + '_donations.json' png_file_name = donating_org.replace(' ', '_') + '_donations.png' vis.to_json(json_file_name) # Transforms the vega json into a donor map image using the vg2png command line function os.system("vg2png " + json_file_name + " " + png_file_name)
import vincent world_countries = r'world-countries.json' world = vincent.Map(width=1200, height=1000) world.geo_data(projection='winkel3', scale=200, world=world_countries) world.to_json(path)
# -*- coding: utf-8 -*- ''' Builds a Vega grammar specification from vincent.Map(), performs shapefile conversion with the Ogre web tool: http://ogre.adc4gis.com/ ''' import vincent #Add Oceans vis = vincent.Map(width=1200, height=800) vis.geo_data(scale=200, spatial_convert=True, ocean=r'data/ne_110m_ocean.zip') vis += ('#75b9e7', 'marks', 0, 'properties', 'enter', 'fill', 'value') vis.update_vis(padding={'bottom': 20, 'left': 50, 'right': 20, 'top': 50}) #Add Land vis.geo_data(spatial_convert=True, world=r'data/ne_110m_land.zip') vis += ('1a252f', 'marks', 1, 'properties', 'enter', 'fill', 'value') #Add Lakes vis.geo_data(spatial_convert=True, lakes=r'data/ne_50m_lakes.zip') vis += ('#3498db', 'marks', 2, 'properties', 'enter', 'fill', 'value') vis.to_json(path, html=True)
'Venezuela' ]), 'country_alpha3': np.array([ 'AIA', 'ATG', 'ARG', 'ABW', 'BHS', 'BRB', 'BLZ', 'BMU', 'BOL', 'VGB', 'CAN', 'CYM', 'CHL', 'COL', 'CRI', 'CUB', 'CUW', 'DMA', 'DOM', 'ECU', 'SLV', 'FLK', 'GRL', 'GRD', 'GTM', 'GUY', 'HTI', 'HND', 'JAM', 'MEX', 'MSR', 'NIC', 'PAN', 'PRY', 'PER', 'PRI', 'BLM', 'KNA', 'LCA', 'MAF', 'SPM', 'VCT', 'SXM', 'SUR', 'TTO', 'TCA', 'USA', 'VIR', 'URY', 'VEN' ]) }) country_data_tmp.head() #map drawing bit Input[2] from your notebook #Note the changes in variable names world_topo = r'world-countries.topo.json' geo_data = [{ 'name': 'countries', 'url': world_topo, 'feature': 'world-countries' }] vis = vi.Map(data=country_data_tmp, geo_data=geo_data, scale=1100, data_key='country_alpha3', map_key={'countries': 'id'}) vis.display()
import json, vincent import pandas as pd with open('us_states.topo.json', 'r') as f: get_id = json.load(f) df = pd.read_csv('prevalence.csv',na_values=[' ']) geo_data = [{'name':'states','url':'us_states.topo.json','feature':'us_states.geo'}] vis = vincent.Map(data=df,geo_data=geo_data,scale=1000,projection='albersUsa', data_bind='Prevalence', data_key='Prevalence', map_key={'states':'properties.NAME'}) vis.display() vis.to_json('vega.json', html_out=True,html_path='vega_tmp.html')
dict_values = country_dict[donor] sorted_x = sorted(dict_values.items(), key=operator.itemgetter(1), reverse=True) geo_data = [{'name': 'countries', 'url': 'https://raw.githubusercontent.com/wingmanzz/Python-Visualizations/master/world-countries.topo.json', 'feature': 'world-countries'}] country_dict[donating_org] = addNonFlowCountries(country_dict[donating_org], get_id) receiving_df = pd.DataFrame(list(country_dict[donating_org].iteritems()), columns=['iso_a3', 'total_received']) merged = pd.merge(receiving_df, country_df, on='iso_a3', how='inner') # Uses vincent to create a map in vega format vis = vincent.Map(data=merged, geo_data=geo_data, brew="Greens", projection='times', scale=250, data_bind='total_received', data_key='iso_a3', map_key={'countries': 'id'}) vis.padding = {'top': 210, 'left': 80, 'bottom': 250, 'right': 80} json_file_name = donating_org.replace(' ', '_') + '_donations.json' png_file_name = donating_org.replace(' ', '_') + '_donations.png' vis.to_json(json_file_name) # Transforms the vega json into a donor map image using the vg2png command line function os.system("vg2png " + json_file_name + " " + png_file_name) donating_org = donating_org.replace("'","") #sets title os.system("convert " + png_file_name + " -pointsize 26 -gravity north -annotate +10+33 'Distribution of " + donating_org + "'\\''" + "s Official Development Assistance (ODA), " + str(start_year) + "-" + str(end_year) + "' " + png_file_name) #sets 'top 10 partner countries' text
!curl -v -X HEAD http://mashupguide.net/wwod14/world-countries.json # <codecell> # https://vincent.readthedocs.org/en/latest/quickstart.html #world_topo = r'https://raw.github.com/trifacta/vega/gh-pages/data/world-countries.json' # CORS enabled #world_topo = r'http://mashupguide.net/wwod14/world-countries.topo.json' world_topo = "files/vincent_map_data/world-countries.topo.json" geo_data = [{'name': 'countries', 'url': world_topo, 'feature': 'world-countries'}] vis = vincent.Map(geo_data=geo_data, scale=200) vis # <codecell> vis.display() # <codecell> vis.to_json('world_map.json', html_out=True, html_path='vincent_world_map.html') # <markdowncell> # When I load vincent_world_map.html -- I don't see a map. I see in JS console: "Uncaught TypeError: Cannot read property 'world-countries' of undefined " # <codecell>
#Grab the State Names and load them into a dataframe, also not neccesary but good practice :) geometries = get_id['objects']['us_states.geo']['geometries'] state_names = [x['properties']['NAME'] for x in geometries] state_df = pd.DataFrame({'NAME': state_names}, dtype=str) #Read into Dataframe, cast to string for consistency df = pd.read_csv('state_data.csv', delimiter=',') df['NAME'] = df['State'].astype(str) #Perform an inner join, pad NA's with data from nearest county merged = pd.merge(df, state_df, on='NAME', how='inner') merged = merged.fillna(method='pad') state_topo = r'us_states.topo.json' geo_data = [{'name': 'states', 'url': state_topo, 'feature': 'us_states.geo'}] #create Map of states color coded based upon mean tweet sentiment vis = vince.Map(data=merged, geo_data=geo_data, scale=1100, projection='albersUsa', data_bind='Mean Sentiment', data_key='NAME', map_key={'states': 'properties.NAME'}) vis.marks[0].properties.enter.stroke_opacity = vince.ValueRef(value=0.5) vis.rebind(column='Mean Sentiment', brew='YlGnBu') vis.scales['color'].type = 'threshold' vis.scales['color'].domain = [-1.0, -0.48, 0.04, 0.56, 1.08, 1.6, 2.11] vis.legend(title='States by Mean Sentiment') vis.to_json('vega_state_map.json')
import vincent data = pd.read_csv( "c:/Users/DCUK/.PyCharmCE2018.1/PycharmProjects/Aspnet_user/country_map.csv" ) col = ["country", "z"] data = data[col] world_countries = r'world-countries.json' geo_data = [{ 'name': 'countries', 'url': world_countries, 'feature': 'world-countries' }] vis = vincent.Map(data=data, geo_data=geo_data, scale=1100, data_bind='z', data_key='country', map_key={'countries': 'id'}) from IPython.display import display vis.display() print(vis) vis.to_json( "c:/Users/DCUK/.PyCharmCE2018.1/PycharmProjects/Aspnet_user/map.json") world = vincent.Map(width=1200, height=1000) world.geo_data(projection='winkel3', scale=200, world=world_countries) import json
def data_map(): return_dict = {} income = request.args.get("income") housing = request.args.get("housing") diversity = request.args.get("diversity") urbanization = request.args.get("urbanization") state = request.args.get("state") statename = request.args.get("statename").replace(" ","_") global df_final fit = [] fit.append(float(income)/100) fit.append(float(housing)/100) fit.append(float(diversity)/100) fit.append(float(urbanization)/100) df_final['fit'] = df_final.apply(lambda x: abs(fit[0]-x['diversity_index'])+abs(fit[1]-x['housing_index'])+abs(fit[2]-x['income_index'])+abs(fit[3]-x['urban_index']),axis=1) if state == 'ZZ': zip_topo = r'/data/zips' state_topo = r'/data/states' geo_data = [{'name': 'states', 'url': state_topo, 'feature': 'us_states.geo'}, {'name': 'zip_codes', 'url': zip_topo, 'feature': 'zip_codes_for_the_usa'}] vis = vincent.Map(data=df_final, geo_data=geo_data, scale=800, projection='albersUsa', data_bind='fit', data_key='zip5',brew='YlOrRd', map_key={'zip_codes': 'properties.zip'}) del vis.marks[0].properties.update vis.marks[1].properties.enter.stroke_opacity = ValueRef(value=0.05) vis.marks[0].properties.enter.stroke.value = '#C0C0C0' vis.legend(title='Preferred ZipCode') return_dict[0] = json.loads(vis.to_json()) ziplist = json.loads(df_final[['ZCTA5','ZIPName','fit']].sort(['fit']).reset_index().head(5).to_json()) table_data = [] for i in range (5): dict_row = {} dict_row['index'] = i dict_row['ZCTA5'] = ziplist['ZCTA5'][str(i)] dict_row['ZIPName'] = ziplist['ZIPName'][str(i)] table_data.append(dict_row) return_dict[1] = table_data #with open ('data.json','w') as outfile: # json.dump(lst,outfile) return json.dumps(return_dict) else: zip_topo = r'/data/state_map?state='+statename feature_name = statename+r'.geo' global land_area rank = int(land_area[statename]) if rank > 0 and rank <=1: scale = 700 elif rank >1 and rank <=3: scale = 2500 elif rank >2 and rank <=19: scale = 3000 elif rank >19 and rank <=26: scale = 4000 elif rank >26 and rank <=39: scale = 4500 elif rank >39 and rank <=40: scale = 5000 elif rank >40 and rank <=48: scale = 6000 else: scale = 23000 geo_data = [{'name': 'state', 'url': zip_topo, 'feature': feature_name}, {'name': 'zip_codes', 'url': zip_topo, 'feature': feature_name}] vis = vincent.Map(data=df_final[df_final['State']==state],geo_data=geo_data, scale=scale, projection='equirectangular', data_bind='fit', data_key='zip5',brew='YlOrRd', map_key={'zip_codes': 'id'}) del vis.marks[0].properties.update #vis.marks[0].properties.enter.stroke.value = '#C0C0C0' vis.marks[1].properties.enter.stroke_opacity = ValueRef(value=0.5) #vis.legend(title='Preferred ZipCode') return_dict[0] = json.loads(vis.to_json()) ziplist = json.loads(df_final[['ZCTA5','ZIPName','fit']][df_final['State']==state].sort(['fit']).reset_index().head(5).to_json()) table_data = [] for i in range (5): dict_row = {} dict_row['index'] = i dict_row['ZCTA5'] = ziplist['ZCTA5'][str(i)] dict_row['ZIPName'] = ziplist['ZIPName'][str(i)] table_data.append(dict_row) return_dict[1] = table_data return json.dumps(return_dict)
# -*- coding: utf-8 -*- ''' Builds a Vega grammar specification from vincent.Map() ''' import vincent import pandas as pd state_geo = r'data/us-states.json' county_geo = r'data/us-counties.json' world_countries = r'data/world-countries.json' path = r'vega.json' #Simple map of the US states = vincent.Map(width=1000, height=800) states.geo_data(projection='albersUsa', scale=1000, states=state_geo) states.to_json(path, html=True) #Simple map of the world world = vincent.Map(width=1200, height=1000) world.geo_data(projection='winkel3', scale=200, world=world_countries) world.to_json(path) #Map with both US States and Counties vis = vincent.Map(width=1000, height=800) #Add our county data first vis.geo_data(projection='albersUsa', scale=1000, counties=county_geo) vis += ('2B4ECF', 'marks', 0, 'properties', 'enter', 'stroke', 'value') #The projection and scale will stay fixed unless you 'reset' the map vis.geo_data(states=state_geo)
def setup(self): '''Setup method''' self.testmap = vincent.Map()