def neighbourhood_map(case_type): df = cases_df(case_type) geo_json = neighbourhood_geojson(df) start_coords = (43.72, -79.39) toronto_map = folium.Map(location=start_coords, zoom_start=11) choropleth = folium.Choropleth( geo_data=geo_json, name="Recent Toronto Covid-19", data=df, columns=['Neighbourhood ID', 'Case Count'], key_on='feature.properties.AREA_SHORT_CODE', fill_color='Reds', bins=9, fill_opacity=0.7, lin_opacity=0.2, highlight=True, legend_name='Toronto Area Covid-19 Recent Cases', ).add_to(toronto_map) choropleth.geojson.add_child( folium.features.GeoJsonTooltip( fields=['AREA_NAME', 'COVID_COUNT'], aliases=['Neighborhood: ', 'Recent Covid-19 Cases: '], style= "background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;" )) toronto_map.keep_in_front(choropleth) folium.LayerControl().add_to(toronto_map) #toronto_map.save(outfile=r'C:\temp\toronto_map.html') return toronto_map
def seoul_map(option): menu = { 'ho': 0, 'da': 1, 'ml': 0, 'se': 0, 'co': 1, 'cg': 0, 'cr': 0, 'st': 0, 'wc': 0 } geo_data = json.load( open('./static/data/skorea_municipalities_geo_simple.json', encoding='utf8')) start_date = request.args.get('startDate', '2020-01-01') end_date = request.args.get('endDate', datetime.now().strftime('%Y-%m-%d')) cdf_raw, _ = cu.make_corona_raw_df(start_date, end_date) cdf = cu.make_corona_df(cdf_raw) html_file = os.path.join(current_app.root_path, 'static/img/seoul_corona.html') map = folium.Map(location=[37.5502, 126.982], zoom_start=11, tiles='Stamen Toner') if option == 'ratio': folium.Choropleth(geo_data=geo_data, data=cdf['천명당 확진자 수'], columns=[cdf.index, cdf['천명당 확진자 수']], fill_color='YlGnBu', key_on='feature.id').add_to(map) else: folium.Choropleth(geo_data=geo_data, data=cdf['누적'], columns=[cdf.index, cdf['누적']], fill_color='PuRd', key_on='feature.id').add_to(map) map.save(html_file) mtime = int(os.stat(html_file).st_mtime) option_str = '천명당 확진자 수' if option == 'ratio' else '누적 확진자 수' return render_template('covid/seoul_map.html', menu=menu, weather=get_weather_main(), mtime=mtime, option_str=option_str)
def heat_map(dataframe, title, area_column, data_column, good_indicator=False, rename_mapping=None): """ Plot number of inspections per community area as a heatmap :param dataframe: dataframe containing area numbers and used data :param title: Title of the heatmap :param area_column: Column of the dataframe containing area information :param data_column: Column of the dataframe containing data :return: folium heatmap of inspections per area """ if good_indicator: colors = "YlGn" else: colors = "YlOrRd" if rename_mapping: dataframe = dataframe.rename(columns=rename_mapping) if data_column in rename_mapping.keys(): data_column = rename_mapping[data_column] #load new map map_chicago = create_chicago_map() #load region data regiondata = json.load(open(cst.AREAS_GEOJSON_PATH)) for feat in regiondata['features']: feat['properties']['community'] = feat['properties'][ 'community'].title() if dataframe[dataframe[area_column] == feat['properties'] ['area_numbe']].empty: feat['properties'][data_column] = 'NaN' else: feat['properties'][data_column] = str( dataframe[dataframe[area_column] == feat['properties'] ['area_numbe']][data_column].values[0]) #create heatmap choro = folium.Choropleth(geo_data=regiondata, data=dataframe, columns=[area_column, data_column], key_on='feature.properties.area_numbe', fill_color=colors, fill_opacity=0.7, nan_fill_color='grey', line_opacity=0.2, legend_name=title).add_to(map_chicago) choro.geojson.add_child( folium.features.GeoJsonTooltip(['community', data_column])) return map_chicago
def build_atx_map_for_single_attribute(year, statistic): year_stat_df = retrieve_values_for_zip_codes(year, statistic) year_stat_df.reset_index(drop=True, inplace=True) year_stat_df = year_stat_df.sort_values(by=['Zip Code']) # GeoJSON of the zip codes for Austin, Tx geo_data = 'atx_zips_coords_ordered.json' # From https://towardsdatascience.com/using-folium-to-generate-choropleth-map-with-customised-tooltips-12e4cec42af2 with open(geo_data) as f: map_datax = json.load(f) map_data = map_datax # prepare the customized text for the tooltip tooltip_text = [] for idx in range(0, len(year_stat_df)): tooltip_text.append(year_stat_df['Zip Code'][idx] + ' ' + str(year_stat_df['Attr Value'][idx])) tooltip_text # Append a tooltip column with customized text for idx in range(0, len(tooltip_text)): map_data['features'][idx]['properties']['tooltip1'] = tooltip_text[idx] geo_data = map_data # Create a folium map object # ATX coordinates: 30.2672° N, 97.7431° W m = folium.Map(location=[30.2672, -97.7431], tiles='Stamen Toner', zoom_start=10) # Now to render the zip codes on the map as Choropleth choropleth = folium.Choropleth(geo_data=geo_data, name='atx choropleth', data=year_stat_df, columns=['Zip Code', 'Attr Value'], key_on='feature.properties.ZCTA5CE10', fill_color='YlGn', fill_opacity=0.7, line_opacity=0.2, legend_name=statistic).add_to(m) # Remember to add layer control folium.LayerControl().add_to(m) # Display Region Label # choropleth.geojson.add_child( choropleth.geojson.add_child( folium.features.GeoJsonTooltip(fields=['tooltip1'], labels=False)) # Save map as html m.save('map.html') srcDoc = open('map.html', 'r', encoding='utf-8') source_code = srcDoc.read() return source_code
def generateMap(): # Generate parishes parishes = os.path.join('mapdata', 'jamaicapolygonmap.geojson') updateMapData() # Create Parish Dataframe parishDf = pd.DataFrame.from_dict(parishData) nil = gpd.read_file(parishes) nil = nil[['id', 'geometry']] nilpop = nil.merge(parishDf, on="id") nil.head() # Create a map object m = folium.Map(location=[18.169340, -77.336837], zoom_start=9) bins = list(parishDf['cases'].quantile([0, 0.4, 0.6, 0.8, 1])) fol_legend( folium.Choropleth(geo_data=parishes, data=parishDf, columns=['id', 'cases'], key_on='feature.id', fill_color='YlOrRd', fill_opacity=0.7, line_opacity=0.2, control=False, legend_name='COVID-19 Cases Per Parish', bins=bins, reset=True)).add_to(m) folium.LayerControl().add_to(m) for key in m._children: if key.startswith('color_map'): del (m._children[key]) style_func = lambda x: { 'fillColor': '#ffffff', 'color': '#000000', 'fillOpacity': 0.1, 'weight': 0.1 } highlight_func = lambda x: { 'fillColor': '#000000', 'color': '#000000', 'fillOpacity': 0.50, 'weight': 0.1 } cases_highlight = folium.features.GeoJson( nilpop, style_function=style_func, control=False, highlight_function=highlight_func, tooltip=folium.features.GeoJsonTooltip( fields=['id', 'cases'], aliases=['Parish: ', 'Cases'], style= ("background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;" ))) #Generate map m.add_child(cases_highlight) m.keep_in_front(cases_highlight) folium.LayerControl().add_to(m) map_path = 'maps/map.html' m.save('maps/map.html')
def homepage(): dengue_data = pd.read_csv("../data/complete_data.csv") # Default to the first item in our select list if (MONTH_KEY not in session): session[MONTH_KEY] = "January" if (YEAR_KEY not in session): session[YEAR_KEY] = 1990 # Persist the values selected by the user in their session if request.method == 'POST': session.clear() session[MONTH_KEY] = str(request.form[MONTH_KEY]) session[YEAR_KEY] = int(request.form[YEAR_KEY]) # Convert the month and year to the proper format for parsing the dataframe date = format_for_date_column(session[MONTH_KEY], session[YEAR_KEY]) filtered_data = dengue_data[dengue_data[DATE_COLUMN] == date] # Set the coordinates and zoom so we can see both points start_coords = (10.7437, -73.2516) folium_map = folium.Map(location=start_coords, zoom_start=4) # Add a map layer to allow for a heat map using the GeoJSON we created folium.Choropleth(geo_data="iquitos_san_juan_geo.json", name='Iquitos and San Juan Dengue Cases', data=filtered_data, columns=[CITIES_COLUMN, DENGUE_CASES_COLUMN], key_on='feature.properties.name', fill_color='YlOrRd', fill_opacity=0.7, line_opacity=0.2, legend_name='Number of Dengue Cases', show=True).add_to(folium_map) folium.LayerControl().add_to(folium_map) # Iquitos Marker creation iquitos_data = filtered_data[filtered_data[CITIES_COLUMN] == "Iquitos"] coordinates = [-3.7437, -73.2516] create_info_marker(iquitos_data, coordinates, folium_map) # San Juan Marker creation san_juan_data = filtered_data[filtered_data[CITIES_COLUMN] == "San Juan"] coordinates = [18.4655, -66.1057] create_info_marker(san_juan_data, coordinates, folium_map) date_selected = { "month_selected": session[MONTH_KEY], "year_selected": session[YEAR_KEY] } folium_map.save('templates/map.html') return render_template("index.html", data=date_selected)
def InteractiveMap(geodata, column_name, transport_method, bins): """ Creates an interactive map of the column that you want to visualise using folium. Takes geodataframe, the column name, transport method as a string and the bins for classification (list of numbers that are the upper limit of each class) as parameters. """ #add a basemap m = folium.Map(location=[60.25, 24.8], tiles='cartodbpositron', zoom_start=10, control_scale=True, attribution="Data: Helsinki Travel Time Matrix") #add the choropleth folium.Choropleth( geo_data=geodata, name="Travel times" + transport_method, data=geodata, columns=["YKR_ID", column_name], key_on="feature.properties.YKR_ID", bins=bins, fill_color="RdYlBu", fill_opacity=0.7, line_opacity=0.2, line_color="white", line_weight=0, highlight=True, legend_name="Travel times by " + transport_method + ", in minutes", ).add_to(m) #add tooltips (info when hovering over) as geoJson folium.GeoJson(geodata, name="travel time", smooth_factor=2, style_function=lambda x: { 'weight': 0.01, 'color': '#807e7e', 'fillOpacity': 0 }, highlight_function=lambda x: { 'weight': 1.5, 'color': 'black' }, tooltip=folium.GeoJsonTooltip( fields=["YKR_ID", column_name], labels=True, sticky=False)).add_to(m) #display layer control folium.LayerControl().add_to(m) #save and return the map outfp = "outputs/traveltimes" + transport_method + ".html" m.save(outfp) display(m) return m
def top_rated_by_country_map(): url = 'data/custom.geo.json' world_geo = f'{url}' world_map = folium.Map(min_zoom=1, max_zoom=6, zoom_start=2, location=(40, 15)) conn = sqlite3.connect("data/movies.db") df = pd.read_sql_query( "Select *, Count(m.country) as count from Country c Join Location l on (c.country_id = l.id) Join Movies m on (c.country_id = m.country) where m.rank>=1 and m.rank<=250 group by m.country", conn) # df.dropna(axis='rows',inplace=True) df['e'] = df.iloc[:, 2:31].sum(axis=1) df = df[['country_name', 'iso_2', 'iso_3', 'long', 'lat', 'e', 'count']] # df.dropna(axis='columns',inplace=True) df = df[df['e'] != 0] conn.close() choropleth = folium.Choropleth( geo_data=world_geo, name='Number of Produced Movies', data=df, columns=['iso_3', 'e'], key_on='feature.properties.iso_a3', fill_color='YlGn', fill_opacity=0.7, line_opacity=0.2, bins=8, legend_name='Number of Produced Movies').add_to(world_map) choropleth.geojson.add_child( folium.features.GeoJsonTooltip(fields=['sovereignt'], labels=False)) incidents = plugins.MarkerCluster( name='Distribution of 250 Top Rated Movies').add_to(world_map) for lat, lng, label, in zip(df.lat, df.long, df['count']): for i in range(label): folium.Marker( location=[lat, lng], icon=plugins.BeautifyIcon(icon="leaf", iconSize=[36, 36], background_color="#87CEFA", border_color="#B0E0E6", borderWidth=5, inner_icon_style='size : 18px', number=label), popup=label, ).add_to(incidents) i += 1 world_map.add_child(incidents) folium.LayerControl().add_to(world_map) return world_map
def makeSingleFDOutlineMap(output_dir, bg_filepath, fd_filepath, geojson_key, map_filename, data, column, bg_info_col_name, casual_name, color="YlOrRd"): """ Creates choloropleth map of single value with toggleable fire district outlines. Inputs: """ # Change block group to string type for mapping data['Block_Group'] = data['Block_Group'].astype(str) data['Block_Group'] = data['Block_Group'].str[:12] fmap = folium.Map(location=[29.72, -95.60], tiles='cartodbpositron', zoom_start=10) folium.Choropleth(geo_data=bg_filepath, data=data, columns=['Block_Group', column], key_on=geojson_key, name=casual_name+" Map", fill_color=color, fill_opacity=1, line_opacity=0.2, nan_fill_color='White', legend_name=bg_info_col_name).add_to(fmap) style_function = lambda x: {'fillColor': '#ffffff', 'color':'black', 'fillOpacity': 0.1, 'weight': 2} highlight_function = lambda x: {'fillColor': '#000000', 'color':'#000000', 'fillOpacity': 0.30, 'weight': 2} # Create data frame of admin dist to polygon fd_geo_df = gpd.read_file(fd_filepath, driver='GeoJSON') fd_geo_df = fd_geo_df[['Fire_Districts.AdminDist', 'geometry']] # Add block group and fire district outlines folium.GeoJson( fd_geo_df, show=False, style_function = style_function, highlight_function = highlight_function, tooltip=folium.GeoJsonTooltip( fields=['Fire_Districts.AdminDist'], aliases=['District Number'], localize=True ), name='Fire District').add_to(fmap) bg_geo_df = make_bg_geo_data(bg_filepath, data) folium.GeoJson( bg_geo_df, highlight_function=highlight_function, style_function = lambda x: { 'color': 'gray', 'weight': 1, 'fillOpacity': 0 }, tooltip=folium.GeoJsonTooltip( fields=['Block_Group', column], aliases=['Block Group', bg_info_col_name], localize=True ), name='Block Group Information').add_to(fmap) LayerControl(collapsed=False).add_to(fmap) fmap.save(output_dir+"/"+map_filename+".html")
def draw_balti_border(i_final_map,g1,i_type): #Add chloropleth layer: optional folium.Choropleth( geo_data='baltimore.json', name='choropleth', data=df_neighood, columns=['Name', 'Population'], key_on='feature.properties.name', fill_color='YlGn', fill_opacity=0.4, line_opacity=0.1, legend_name='Population').add_to(i_final_map) #Create Style function for GeoJson method style_function = lambda x: { 'fill_color':'YlGn', 'color':'black', 'weight':0.8, 'line_opacity':0.0, 'fillOpacity': 0.0 } if(i_type=='analysis'): print(i_type) #Create Style function for GeoJson method g1.add_child(folium.GeoJson( df_geojson, style_function=style_function, tooltip=folium.GeoJsonTooltip( fields=['name', 'White','Blk_AfAm','Crime_Count','Police_Count','Detected_Crime_Count'], aliases=['Neighbourhood','White','Blk_AfAm','Crime_Count','Police_Count','Detected_Crime_Count'], localize=True ) )) else: g1.add_child(folium.GeoJson( df_geojson, style_function=style_function, tooltip=folium.GeoJsonTooltip( fields=['name','Male','Female', 'White','Blk_AfAm','AmInd_AkNa','Asian','NatHaw_Pac','Other_Race','TwoOrMore','Hisp_Lat'], aliases=['Neighbourhood','Male Population','Female Population','White','Blk_AfAm','AmInd_AkNa','Asian','NatHaw_Pac','Other_Race','TwoOrMore','Hisp_Lat'], localize=True ) )) i_final_map.add_child(feature_group) i_final_map.add_child(g1) #Inorder to know labels in map while zooming we can use the followig: optional folium.map.CustomPane('labels').add_to(i_final_map) folium.TileLayer('CartoDBPositronOnlyLabels', pane='labels').add_to(i_final_map) return (i_final_map)
def map(): text = mapper() m = folium.Map(location=[41.0082, 20], zoom_start=1.5, min_zoom=2) folium.Choropleth( geo_data=text, fill_color='red', fill_opacity=0.3, line_weight=2, ).add_to(m) return m.get_root().render()
def map_display(map, map_result, column_to_check, legend_text): folium.Choropleth(geo_data=map_result, name='choropleth', data=map_result, columns=[column_to_check, 'Counts'], key_on='feature.properties.name', fill_color='OrRd', fill_opacity=0.7, line_opacity=0.2, legend_name=legend_text).add_to(map)
def worldmap(): # 전처리된 엑셀 파일 tkinter.messagebox.showinfo('messagebox', '전처리된 엑셀 파일을 선택하시오.') filepath = filedialog.askopenfilename(initialdir="/", title="엑셀 파일 선택", filetypes=(("Excel files", "*.xlsx"), ("all files", "*.*"))) mapdata = pd.read_excel(filepath) 출원인국가코드counts = mapdata['출원인국가코드'].value_counts() 출원인국가코드counts = 출원인국가코드counts.reset_index() 출원인국가코드counts.columns = ['출원인국가코드', '출원건수'] # 국가코드 파일 tkinter.messagebox.showinfo('messagebox', '국가코드 파일을 선택하시오.') codepath = filedialog.askopenfilename(initialdir="/", title="엑셀 파일 선택", filetypes=(("Excel files", "*.xlsx"), ("all files", "*.*"))) 출원인국가코드data = pd.read_excel(codepath) # 출원인국가코드counts + 출원인국가코드data worlddata = pd.merge(출원인국가코드counts, 출원인국가코드data, how='left', on='출원인국가코드') # JSON 파일 tkinter.messagebox.showinfo('messagebox', 'jSON 파일을 선택하시오.') jsonpath = filedialog.askopenfilename(initialdir="/", title="엑셀 파일 선택", filetypes=(("json files", "*.json"), ("all files", "*.*"))) jsonfile = json.load(open(jsonpath, encoding='utf-8')) map = folium.Map(location=[32.3468904, 6.1352215], tiles='CartoDB dark_matter', zoom_start=2) # 지도 작성 folium.Choropleth(geo_data=jsonfile, data=worlddata, columns=['영문명', '출원건수'], fill_color='YlGn', fill_opacity=0.7, line_opacity=0.5, key_on='properties.PLACENAME').add_to(map) folium.GeoJson(jsonfile, style_function=style_function).add_to(map) tkinter.messagebox.showinfo('messagebox', '지도를 저장할 위치를 선택하시오.') mapsave = filedialog.asksaveasfilename(initialdir="/", title="저장 위치 선택", filetypes=(("Html files", "*.html"), ("all files", "*.*"))) map.save('{}.html'.format(mapsave))
def makeInteractiveMap(output_dir, data, bg_filepath, fd_filepath): fmap = folium.Map(location=[29.72, -95.60], name="Map", tiles='cartodbpositron', zoom_start=10, control=False, overlay=False) for column in columns: data[column] = data[column].round().astype(int) folium_del_legend(folium.Choropleth(geo_data=bg_filepath, overlay=False, show = False, name=column, data=data, threshold_scale = [0, 5, 10, 20, 30, 40, 50, 60, 80, 101], columns=['Block_Group', column], key_on='feature.properties.Name', fill_color='YlOrRd', fill_opacity=1, line_opacity=0.2, nan_fill_color='White', legend_name=column)).add_to(fmap) # Adds a legend - doesn't change existing values though colormap = branca.colormap.linear.YlOrRd_09.scale(0, 90) colormap.caption = 'Proportion out of Total Calls' colormap.add_to(fmap) # Add block group outline with open(bg_filepath) as f: bg = json.load(f) folium.GeoJson( bg, style_function = lambda x: { 'color': 'gray', 'weight': 1, 'fillOpacity': 0 }, name='Block Group Boundaries').add_to(fmap) style_function = lambda x: {'fillColor': '#ffffff', 'color':'black', 'fillOpacity': 0.1, 'weight': 2} highlight_function = lambda x: {'fillColor': '#000000', 'color':'#000000', 'fillOpacity': 0.30, 'weight': 2} # Create data frame of admin dist to polygon fd_geo_df = gpd.read_file(fd_filepath, driver='GeoJSON') fd_geo_df = fd_geo_df[['Fire_Districts.AdminDist', 'geometry']] # Add block group and fire district outlines folium.GeoJson( fd_geo_df, show=False, style_function = style_function, highlight_function = highlight_function, tooltip=folium.GeoJsonTooltip( fields=['Fire_Districts.AdminDist'], aliases=['District Number'], localize=True ), name='Fire District').add_to(fmap) LayerControl(collapsed=False).add_to(fmap) fmap.save(output_dir+"/interactive-map.html")
def seoul_map(option): geo_data = json.load( open('./static/data/skorea_municipalities_geo_simple.json', encoding='utf8')) # 최근 1년치 데이터만 보여주기 위해 수정 today = date.today() last_month = 1 if today.month == 12 else today.month + 1 last_date = date(today.year - 1, last_month, 1) start_date = request.args.get('startDate', last_date.strftime('%Y-%m-%d')) end_date = request.args.get('endDate', today.strftime('%Y-%m-%d')) cdf_raw, _ = cu.make_corona_raw_df(start_date, end_date) cdf = cu.make_corona_df(cdf_raw, last_month) ################### html_file = os.path.join(current_app.root_path, 'static/img/seoul_corona.html') map = folium.Map(location=[37.5502, 126.982], zoom_start=11, tiles='Stamen Toner') if option == 'ratio': folium.Choropleth(geo_data=geo_data, data=cdf['천명당 확진자 수'], columns=[cdf.index, cdf['천명당 확진자 수']], fill_color='YlGnBu', key_on='feature.id').add_to(map) else: folium.Choropleth(geo_data=geo_data, data=cdf['누적'], columns=[cdf.index, cdf['누적']], fill_color='PuRd', key_on='feature.id').add_to(map) map.save(html_file) mtime = int(os.stat(html_file).st_mtime) option_str = '천명당 확진자 수' if option == 'ratio' else '누적 확진자 수' return render_template('covid/seoul_map.html', menu=menu, weather=get_weather_main(), mtime=mtime, option_str=option_str)
def show_Choropleth(self, dataFrame): geo_path = 'D:/AtomProject/python/section7/skorea_geo_simple.json' # 파일 역직렬화 geo_data = json.load(open(file = geo_path, mode = 'r', encoding = 'UTF-8')) # 지도 생성 map = folium.Map(location = [37.5502, 126.982], zoom_start = 10.5, tiles= 'Stamen Toner') # Choropleth 이식 folium.Choropleth(geo_data = geo_data, data = dataFrame, columns = [dataFrame.index, '가격'], key_on = 'feature.id', fill_color='PuRd').add_to(map) # Choropleth map 저장 map.save('D:/AtomProject/python/section7/map.html')
def save_folium_map(csv_file="main.csv"): """ Create a map using the available csv file with country data and save it to file. """ state_geo_file = "world-countries.json" df = pd.read_csv(csv_file) state_data = df columns = df.columns[5:] m = folium.Map(location=[0, 0], zoom_start=2, min_zoom=2, max_zoom=5) for cur_column in columns: chlor = folium.Choropleth( geo_data=state_geo_file, name=cur_column, data=state_data, columns=["locale3", cur_column], key_on="feature.id", fill_color="YlGn", fill_opacity=0.7, nan_fill_opacity=0.2, line_opacity=0.2, legend_name=f'%', nan_fill_color="grey", bins=[0.0, 0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 1], highlight=False, overlay=False, show=False, ) # Remove legends if not cur_column == columns[0]: for key in chlor._children: if key.startswith("color_map"): del chlor._children[key] chlor.add_to(m) for lat, lon, locale in zip(df.lat_avg, df.lon_avg, df.index): popup_html = create_popup_table(df, locale) popup = folium.Popup(html=popup_html) icon = folium.features.CustomIcon("circle.png", icon_size=(8, 8)) folium.Marker(location=[lat, lon], icon=icon, popup=popup).add_to(m) folium.LayerControl(collapsed=True).add_to(m) m.save('app/templates/map.html') with open('app/templates/map.html', 'r') as f: text = f.read() text = text.replace('"openstreetmap" : tile_layer', '// "openstreetmap" : tile_layer', 1) with open('app/templates/map.html', 'w') as f: f.write(text) print('Plotting: Map created successfully.') return 1
def avmap(request, listing_id): listing = get_object_or_404(Listing, pk=listing_id) location_lat = float(listing.location_lat) location_lon = float(listing.location_lon) location = listing.location address = listing.address data = pd.read_csv('kc_house_data.csv') data_map = data.groupby('zipcode')[['price']].mean().reset_index() data_map['zipcode'] = data_map['zipcode'].astype(str) k_c = 'new.json' map = folium.Map( location=[47.5577, -122.1277], zoom_start=10.5, detect_retina=True, control_scale=False, ) choropleth = folium.Choropleth(geo_data=k_c, name='choropleth', data=data_map, columns=['zipcode', 'price'], key_on='feature.properties.ZIPCODE', fill_color='Blues', line_color='red', fill_opacity=0.9, line_opacity=0.5, highlight=True, legend_name='Average Price ($)').add_to(map) folium.LayerControl().add_to(map) choropleth.geojson.add_child( folium.features.GeoJsonTooltip(['ZIPCODE'], labels=False)).add_to(map) city = folium.Html('<b>Seattle</b>', script=True) pin = folium.Html('<h1>Property Location -</h1>' + location + address, script=True) popup_1 = folium.Popup(pin, max_width=2650) popup_2 = folium.Popup(city, max_width=2650) folium.Marker(location=[location_lat, location_lon], popup=popup_1, icon=folium.Icon(color="red", icon="home", prefix='fa')).add_to(map) folium.CircleMarker(location=[47.6062, -122.3321], radius=10, popup=popup_2, color='#FF0000', fill=True, fill_color='#FF0000').add_to(map) map = map._repr_html_() context = {'my_map': map, 'location': location} return render(request, 'listings/maps.html', context)
def draw_arrondissement(self, geo, couleur): folium.Choropleth(geo_data=geo, name='choropleth', columns=['latitude', 'longitude'], key_on='feature.id', fill_color=couleur, fill_opacity=0.3, line_opacity=1, line_weight=1, line_color='blue', legend_name='valeurs foncieres').add_to(self.map)
def height_by_divisions(db, grao, points, m, color): print('SHOWING MAP BY ' + grao) print('SHOWING POINTS FOR ' + points) if grao == 'freguesia': final_query = 'SELECT count(*), st_AsGeoJSON(geom), freguesia FROM projBD, cont_aad_caop2017 WHERE st_contains(geom,' + points + ') GROUP BY geom,freguesia;' else: geometry2 = 'st_union(geom) g' aux_query5 = 'SELECT ' + grao + ' d, ' + geometry2 + ' FROM cont_aad_caop2017 GROUP BY ' + grao final_query = 'SELECT count(*), st_AsGeoJSON(st_boundary(coords.g)), coords.d FROM projBD, (' + aux_query5 + ') coords WHERE st_contains(coords.g,' + points + ') GROUP BY coords.g,coords.d;' cursor = db.cursor() cursor.execute(final_query) results = cursor.fetchall() #print(results) weights = [int(res[0]) for res in results] names = [res[2] for res in results] print(weights) print(names) #regions = [res[1] for res in results] col1 = ['Region' + str(i) for i in range(len(results))] d = {'ID': col1, 'Services': weights} data2 = pd.DataFrame(data=d) data2['ID'] = data2['ID'].astype(str) data2['Services'] = data2['Services'].astype(int) finalJSON = '{"type":"FeatureCollection","features":[' i = 0 for res in results: #folium.GeoJson(res[1]).add_to(m) if i > 0: finalJSON += ',' finalJSON += '{"type":"Feature","properties":{"name":"' + names[ i] + '", "id":"Region' + str( i) + '", "style":{"fill":"True"}},"geometry":' + res[1] + '}' i += 1 finalJSON += ']}' #print(finalJSON) print('------') finalJSON = json.loads(finalJSON) #finalJSON2 = finalJSON #print(finalJSON["features"][0]["properties"]) folium.Choropleth(geo_data=finalJSON, data=data2, bins=8, columns=['ID', 'Services'], key_on='feature.properties.id', fill_color=color, legend_name='Taxi Services - ' + points, overlay=True, name=points, show=False, highlight=True).add_to(m)
def plot_numeric_geo_data(data, m, gid, feature): folium.Choropleth( data, data=data, columns=[gid, feature], key_on='feature.properties.{}'.format(gid), fill_color='BuPu', fill_opacity=0.7, line_opacity=0.5, ).add_to(m) return m
def facility_density_map(): combined_df = facilities_per_area() # Create map object (second column denotes which column to use for the values) m = folium.Map(location=[41, -97], zoom_start=5) us_counties = 'https://gist.githubusercontent.com/wrobstory/5586482/raw/6031540596a4ff6cbfee13a5fc894588422fd3e6/us-counties.json' folium.Choropleth(geo_data=us_counties, name='choropleth', data=combined_df, columns=['fips', 'count_total'], key_on='feature.id', fill_color='Reds', fill_opacity=0.8, nan_fill_opacity=0.0, line_opacity=1).add_to(m) m.save('count_total.html') m = folium.Map(location=[41, -97], zoom_start=5) us_counties = 'https://gist.githubusercontent.com/wrobstory/5586482/raw/6031540596a4ff6cbfee13a5fc894588422fd3e6/us-counties.json' folium.Choropleth(geo_data=us_counties, name='choropleth', data=combined_df, columns=['fips', 'count_other'], key_on='feature.id', fill_color='Oranges', fill_opacity=0.8, nan_fill_opacity=0.0, line_opacity=1).add_to(m) m.save('count_other.html') m = folium.Map(location=[41, -97], zoom_start=5) us_counties = 'https://gist.githubusercontent.com/wrobstory/5586482/raw/6031540596a4ff6cbfee13a5fc894588422fd3e6/us-counties.json' folium.Choropleth(geo_data=us_counties, name='choropleth', data=combined_df, columns=['fips', 'count_ice'], key_on='feature.id', fill_color='Blues', fill_opacity=0.8, nan_fill_opacity=0.0, line_opacity=1).add_to(m) m.save('count_ice.html')
def plot_choropleth(m, layer_name, target_column): folium.Choropleth( geo_data=aurin_data, name=layer_name, data=df_properties, columns=['lga_code_2016', target_column], key_on='feature.properties.lga_code_2016', fill_color='YlGn', fill_opacity=0.7, line_opacity=0.2, ).add_to(m)
def add_map_properties(cols, dataset, the_map): try: folium.Choropleth(geo_data=open(r'data\nyc-zip-code.geojson').read(), data=dataset, columns=cols, key_on='feature.properties.postalCode', fill_color='YlOrRd', fill_opacity=0.7, line_opacity=0.2, legend_name='Average Rent').add_to(the_map) except: print('Something went wrong')
def create_coropleth(self, for_geo_data, for_data, for_columns, for_key_on, for_legend): folium.Choropleth(geo_data=for_geo_data, name='choropleth', data=for_data, columns=for_columns, key_on=for_key_on, fill_color='YlGnBu', fill_opacity=0.9, line_opacity=0.2, legend_name=for_legend).add_to(self.geo_map)
def make_choro_map(table, legend_name): map = make_blank_map(11.5) portland_geo_data = r'/Users/will/Desktop/Portland/neighborhoods_regions.geojson' folium.Choropleth(geo_data=portland_geo_data, data=table, columns=['Neighborhood', 'Count'], key_on='properties.MAPLABEL', fill_color='YlOrRd', fill_opacity=0.6, line_opacity=0.4, legend_name=legend_name).add_to(map) return map
def create_map(): # Get the district shapefile and the list of projects that have already been spatially joined to the appropriate congressional district geo_df, projs = get_cd116() # Loop through each district shape # and use the district name to filter the list of projects # to build a map of projects in that district; for i, row in geo_df.iterrows(): #for i, row in nsd.iterrows(): marker_array = [] tmp_df = geo_df[geo_df['district'] == row['district']] tmp_projs = projs[projs['cd116'] == row['district']] print(tmp_projs.head()) # Hawaii's get bounds function is far too wide/large for the state or district, so set bound explicitly # This is not a great way to do this, but works as a first step. # Next step would be to build a dictionary of these bounds that can be filtered by district # Would need to examine each of the districts, perhaps exporting each of the bounds temporarily # in the code below to build a base version if(row['district'] == 'HI-02'): x1 = -160.678701 y1 = 18.927830 x2 = -154.724111 y2 = 22.360977 else: x1, y1, x2, y2 = tmp_df['geom'].iloc[0].bounds print(f"x1: {x1} y1: {y1} x2: {x2} y2: {y2}") # For the base map, use the Mapbox api to access our typical styled tiles map = folium.Map(location=[45.5236, -122.6750], tiles="https://api.mapbox.com/styles/v1/aaronleeh/cjr11cc8j1r602sp26k42ckh9/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoiYWFyb25sZWVoIiwiYSI6IjF0SjNqUUUifQ.0sVfP4L9LWoycJoinMovtA", #API_key='pk.eyJ1IjoiYWFyb25sZWVoIiwiYSI6IjF0SjNqUUUifQ.0sVfP4L9LWoycJoinMovtA', attr="SEIA", zoom_control=False) # Color the district shape to provide a visual reference of the geography folium.Choropleth(geo_str=tmp_df, fill_color='#ffe148', fill_opacity=0.7, geo_data=tmp_df, line_opacity=1, line_color="#ffe148").add_to(map) # Loop through the project data and assign the color and radius based on # the project's status for fill color and capacity for circle radius for i, prow in tmp_projs.iterrows(): marker = makeMarker(prow['status_main'], prow['capacity_seia_mw'], [prow['lat'], prow['lon']]) marker.add_to(map) marker_array.append(marker) legend = getLegend() map.get_root().html.add_child(folium.Element(legend)) #map.get_root().html.add_child(folium.Element(legendCSS())) map.fit_bounds([[y1, x1], [y2, x2]]) map.save(linux_dir + f"html/{row['district']}.html") return
def map_cov(location, state): dis_lat_lon_dir = os.path.join(settings.BASE_DIR, 'Data_files and other codes', 'District Lat Long', state + '_District_lat_long.xlsx') location_df = pd.read_excel(dis_lat_lon_dir) location_cor = location_df.loc[location_df['District'] == location] location_cor = location_cor.drop(['District'], axis=1) location_cor = location_cor.values.tolist() # Normal codes for doing stuffs state_district_wise_case = district_wise_case() select_data_district = [] df2 = { 'Cases': state_district_wise_case.at[12, 'Cases'] + state_district_wise_case.at[9, 'Cases'], 'District': 'Barddhaman' } state_district_wise_case = state_district_wise_case.append( df2, ignore_index=True) state_district_wise_case.sort_values(by='Cases', ascending=False, inplace=True) # Creating dictionary for state/ District wise Data for i in range(int(state_district_wise_case.shape[0])): temp = state_district_wise_case.iloc[i] select_data_district.append(dict(temp)) # Map Data from Static files file_path_choropleth = os.path.join(settings.BASE_DIR, 'static', 'IndiaStateTopojsonFiles-master', 'WestBengal.geojson') map_path = os.path.join(settings.BASE_DIR, 'template', 'covid_map.html') west_bengal_geojson = geopandas.read_file(file_path_choropleth) # Map for the COVID cases choropleth m = folium.Map(location=location_cor[0], tiles='cartodbpositron', zoom_start=8) folium.Choropleth( geo_data=west_bengal_geojson, name="choropleth", data=state_district_wise_case, columns=["District", "Cases"], key_on="feature.properties.Dist_Name", fill_color="YlGn", fill_opacity=0.5, line_opacity=0.2, legend_name="Active covid cases", ).add_to(m) folium.LayerControl().add_to(m) m = m._repr_html_() m.save(outfile=map_path)
def makeChoropleth(m, geo_data, data): choropleth = folium.Choropleth(geo_data=geo_data, name='choropleth', data=data, columns=['State', 'Recursers'], nan_fill_color='grey', nan_fill_opacity=0.4, key_on='feature.id', fill_color='YlGn', legend_name='# of Recursers', highlight=True, fill_opacity=0.5).add_to(m) return choropleth
def agregar_capa(self, nombre_capa, gpd_mapa, df_datos, columnas_datos, nombre_leyenda, llave_mapa='feature.properties.MANZ_CCNCT'): capa=folium.Choropleth( geo_data=gpd_mapa, name=nombre_capa, data=df_datos, columns=columnas_datos, key_on=llave_mapa, fill_color="YlOrRd", fill_opacity=0.7, line_opacity=0.9, legend_name=nombre_leyenda ).add_to(self)