def heatmap(loc_gdf, column="Location Extracted", heat_value=None, normalize_data=True, output_name='heatmap.html', output_dir=''): locations = loc_gdf[column].value_counts().values max_amount = float(locations.max()) if (normalize_data): locations = loc_gdf['Location Extracted'].value_counts().values normalized = (locations - locations.min()) / (locations.max() - locations.min()) hmap = folium.Map(zoom_start=7) hm_wide = HeatMap( list( zip(loc_gdf.Latitude.values, loc_gdf.Longitude.values, normalized)), min_opacity=0.2, radius=17, blur=15, max_zoom=1, ) hmap.add_child(hm_wide) hmap.save(os.path.join(output_dir, 'heatmap.html')) return hmap else: max_amount = float(locations.max()) hmaps = folium.Map(zoom_start=7) hm_wides = HeatMap( list( zip(loc_gdf.Latitude.values, loc_gdf.Longitude.values, locations)), min_opacity=0.2, max_val=max_amount, radius=17, blur=15, max_zoom=1, ) hmaps.add_child(hm_wide) hmap.save(os.path.join(output_dir, 'heatmap.html')) return hmap
def heatmap(df_, n_rows, lat_origin=None, lon_origin=None, zoom_start=12, radius=8, max_zoom=13, base_map=None, save_as_html=False, filename='heatmap.html'): if base_map is None: if lat_origin is None and lon_origin is None: lat_origin = df_.loc[0]['lat'] lon_origin = df_.loc[0]['lon'] base_map = generateBaseMap(default_location=[lat_origin, lon_origin], default_zoom_start=zoom_start) COUNT = 'count' df_[COUNT] = 1 HeatMap(data=df_.loc[:n_rows, ['lat', 'lon', COUNT]].groupby( ['lat', 'lon']).sum().reset_index().values.tolist(), radius=radius, max_zoom=max_zoom).add_to(base_map) df_.drop(columns=[COUNT], inplace=True) if save_as_html: base_map.save(outfile=filename) else: return base_map
def geo_topic(row, Coordinates, index, topic='', save=False, folder='heatmaps'): if topic == '': print "Warning; topic undefined. saving the file under folder/index.html" topic = str(index) x = sorted(set([Cd[0] for Cd in Coordinates])) y = sorted(set([Cd[1] for Cd in Coordinates])) z = [(Coordinates[i], row[i]) for i in range(0, len(row))] hem = np.zeros((len(x), len(y))) for e in z: hem[x.index(e[0][0])][y.index(e[0][1])] = e[1] hmap = folium.Map( location=[np.mean(x), np.mean(y)], zoom_start=10, ) hm_wide = HeatMap( list(zip([C[0] for C in Coordinates], [C[1] for C in Coordinates], row)), min_opacity=0, max_val=max(row), radius=15, blur=0, max_zoom=1, ) hmap.add_child(hm_wide) hmap.render() if save: if folder == 'heatmaps': print 'Warning: No folder name specified. The heatmaps will be saved in a created heatmaps folder' hmap.save(folder + '/heatmap' + topic + '_norm.html')
def draw_map(): update() map_data = pd.read_csv('./Data/us-zip-codes-cleaned.csv') lat = 40.05 lon = -74.40 starting_location = [ lat, lon ] # starting location of the map depending on the inputted zipcode h_map = folium.Map(location=starting_location, zoom_start=8) max_amount = map_data['Risk'].max() hm_wide = HeatMap(list( zip(map_data.Lat.values, map_data.Long.values, map_data.Risk.values)), min_opacity=0.1, max_zoom=9, max_val=max_amount, radius=25, blur=20) # Adds the heatmap element to the map h_map.add_child(hm_wide) # Saves the map to heatmap.html h_map.save(os.path.join('./templates', 'heatmap.html')) # Render the heatmap return render_template('heatmap.html')
def plot_heat_map(df, lat, long, city=None, radius=10, zoom_start=10): df = df[df.filename.str.startswith(city.lower())] coordinates = df[['lat','long']].values m = folium.Map(location=[lat, long],zoom_start=zoom_start) m.add_child(HeatMap(coordinates, radius=radius)) return m
def generateMap(self, settings): """Generates the heatmap. Arguments: settings {dict} -- The settings for the heatmap. Returns: Map -- The Heatmap. """ tiles = settings["tiles"] zoom_start = settings["zoom_start"] radius = settings["radius"] blur = settings["blur"] min_opacity = settings["min_opacity"] max_zoom = settings["max_zoom"] map_data = [(coords[0], coords[1], magnitude) for coords, magnitude in self.coordinates.items()] # Generate map m = folium.Map(location=self.max_coordinates, zoom_start=zoom_start, tiles=tiles) # Generate heat map heatmap = HeatMap(map_data, max_val=self.max_magnitude, min_opacity=min_opacity, radius=radius, blur=blur, max_zoom=max_zoom) m.add_child(heatmap) return m
def test_heat_map(): np.random.seed(3141592) data = (np.random.normal(size=(100, 2)) * np.array([[1, 1]]) + np.array([[48, 5]])) m = folium.Map([48., 5.], tiles='stamentoner', zoom_start=6) hm = HeatMap(data) m.add_child(hm) m._repr_html_() out = normalize(m._parent.render()) # We verify that the script import is present. script = '<script src="https://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js"></script>' # noqa assert script in out # We verify that the script part is correct. tmpl = Template(""" var {{this.get_name()}} = L.heatLayer( {{this.data}}, { minOpacity: {{this.min_opacity}}, maxZoom: {{this.max_zoom}}, max: {{this.max_val}}, radius: {{this.radius}}, blur: {{this.blur}}, gradient: {{this.gradient}} }) .addTo({{this._parent.get_name()}}); """) assert tmpl.render(this=hm) bounds = m.get_bounds() assert bounds == [[46.218566840847025, 3.0302801394447734], [50.75345011431167, 7.132453997672826]], bounds
def mapping(): # 地図の中心を大手町にセット map = folium.Map(location=[35.6553, 139.7571], zoom_start=14) # プロットするデータのリスト list = [] # 浜松町追加 hamamatsu = 100 for _ in range(hamamatsu): list.append([35.6553, 139.7571]) # 赤羽追加 akabane = 40 for _ in range(akabane): list.append([35.777615, 139.7209868]) # 汐留追加 shiodome = 35 for _ in range(shiodome): list.append([35.6629339, 139.7600031]) # データをヒートマップとしてプロット HeatMap(list, radius=40, blur=40).add_to(map) # HTMLを出力 map.save('templates/tmpl.html') return render_template('tmpl.html')
def HMAP(LAT,LONG): with open('Data/NoticiasDataV01.csv') as f: newsvic10=pd.read_csv(f, delimiter=';') with open('Data/COOR_MUN1.csv') as f: COOR_MUN10=pd.read_csv(f, delimiter=',') COOR_MUN10.head(3) newsvic10 = pd.merge(newsvic10,COOR_MUN10, on='CODMUN') #max_amount = float(newsvic['COD_HECHO'].max()) ### CREAR EL MAPA folium_hmap = folium.Map(width=700,height=700, location=[4.688, -74.02], zoom_start=6, tiles="OpenStreetMap") max_amount = 10 hm_wide = HeatMap( list(zip(newsvic10['latitude'], newsvic10['longitude'])), min_opacity=0.2, max_val=max_amount, radius=10, blur=6, max_zoom=15, ) folium_hmap = folium_hmap.add_child(hm_wide) marker = folium.CircleMarker(location=[LAT,LONG],radius=5,color="red",fill=True) marker.add_to(folium_hmap) return folium_hmap
def output_map(self, data, selection, file_path='heatmap01.html'): file_path, data, selection = file_path, data.copy(), selection.copy() self.selected_data = data.copy() for key in selection: lst = self.lst_judge(key, selection, self.selected_data) self.selected_data = self.selected_data.loc[lst, :] self.num = len(self.selected_data) lat = np.array(selected_data["g.parallel_submit"]) lon = np.array(selected_data["g.meridian_submit"]) self.location = [[lat[i], lon[i]] for i in range(self.num)] try: folium except: import folium try: HeatMap except: from folium.plugins import HeatMap map_osm = folium.Map(location=[35, 110], zoom_start=5) HeatMap(self.location).add_to(map_osm) for i, point in zip(self.selected_data.index, self.location): folium.Marker( point, tooltip=('Age:{}'.format( self.selected_data['i.age_val'][i]))).add_to(map_osm) map_osm.save(file_path) print('一共有{}个用户'.format(len(self.location))) print('热点图已保存.')
def dist_heatmap(data_h): lat = np.array(data_h['纬度']) # 获取维度之维度值 lon = np.array(data_h['经度']) # 获取经度值 pop = np.array(data_h['count'], dtype=float) # 获取人口数,转化为numpy浮点型 num = len(data_h) data1 = [[lat[i], lon[i], pop[i]] for i in range(num)] #将数据制作成[lats,lons,weights]的形式 map_osm = folium.Map(location=[32, 110], zoom_start=5, control_scale=True) #绘制Map,开始缩放程度是5倍 HeatMap(data1).add_to(map_osm) # 将热力图添加到前面建立的map里 #为m添加标记部件 folium.Marker([24.457436, 118.087517], popup='Rd. Cenxi', icon=folium.Icon(icon='cloud')).add_to(map_osm) ls = folium.PolyLine(locations=[[27.795574,114.374611],[29.833700,106.429500],\ [22.556396,114.110672],[24.457436,118.087517]],color='blue') ls.add_to(map_osm) map_osm map_osm.save('friend_dist.html') # 保存为html文件
def make_heatmap_ghtorrent(): query = ''' SELECT lat, long, COUNT(*) as count FROM users WHERE (location IS NOT NULL and location !='null') AND (lat != 0 AND long != 0) GROUP BY lat, long HAVING COUNT(*) > 10 ORDER BY count DESC ''' rows = run_query(query) grid = [list(row) for row in rows] hmap = folium.Map(location=[0.0, 0.0], zoom_start=3) hm_wide = HeatMap( grid, min_opacity=0.2, max_val=38000, radius=17, blur=15, max_zoom=1, ) hmap.add_child(hm_wide) hmap.save('heatmap_ghtorrent.html')
def generateMap(self, tiles, map_zoom_start=6, heatmap_radius=7, heatmap_blur=4, heatmap_min_opacity=0.2, heatmap_max_zoom=4): map_data = [(coords[0], coords[1], magnitude) for coords, magnitude in self.coordinates.items()] # Generate map m = folium.Map(location=self.max_coordinates, zoom_start=map_zoom_start, tiles=tiles) # Generate heat map heatmap = HeatMap(map_data, max_val=self.max_magnitude, min_opacity=heatmap_min_opacity, radius=heatmap_radius, blur=heatmap_blur, max_zoom=heatmap_max_zoom) # Marker // 53.582952, 10.029599 marker_w = folium.Marker([53.5829, 10.0295], popup='Work', icon=folium.Icon(color='blue', icon='bar-chart', prefix='fa')) m.add_child(heatmap) m.add_child(marker_w) return m
def graficoincid(): map = folium.Map( location=[-22.866482,-43.221083], zoom_start=12 ) locais=[] snapshots1 = list(db.child("Users").child("DadosGeograficos").get().val()) for snapshots in snapshots1: valor = db.child("Users").child("DadosGeograficos").child(snapshots).get().val() #latitude = valor['Latitude'] #longitude = valor['Longitude'] for item in valor: try: aqui = db.child("Users").child("DadosGeograficos").child(snapshots).child(item).get().val() #latitude = aqui['Latitude'] #longitude = aqui['Longitude'] coord = [aqui['Latitude'], aqui['Longitude']] #print(coord) locais.append(coord) #alerta = aqui['Alerta'].capitalize() except: continue HeatMap(locais, radius=30).add_to(map) return map._repr_html_()
def heat_map(request): from folium.plugins import HeatMap import numpy as np import json #filename = os.path.join('data', 'us-states.json') filename = join(settings.STATIC_ROOT, 'myapp/us-states.json') geo_json_data = json.load(open(filename)) m = folium.Map([43, -100], zoom_start=4) folium.GeoJson(geo_json_data).add_to(m) # randomly generate 100 data points around coordinate [43, -100] data = (np.random.normal(size=(100, 3)) * np.array([[1, 1, 1]]) + np.array([[43, -100, 1]])).tolist() #print(data) # print to console for debugging HeatMap(data).add_to(m) # Instead of saving to a html file, we prepare a map_string # m.save(os.path.join('data', 'Heatmap.html')) map_string = m._repr_html_().replace("width:90%;", "height:60%;float:top;", 1) return render(request, 'view_states.html', { "title": "Heat Map Sample", "map_string": map_string })
def generate_heat_map(_list_data, _only_spain): """ Method to generate a heat map with all the values :param _only_spain: For filtering by Spain or Global :param _list_data: List of values for every day """ logging.info('Start to generate the heat map') try: heat_map = folium.Map(location=[43, 0], zoom_start=f'{5 if _only_spain else 3}', tiles='Stamen Toner', width=f'{"50%" if _only_spain else "100%"}', height=f'{"80%" if _only_spain else "100%"}') location = [] for c in range(0, len(list_data)): for lat, lon in zip(list_data[c]['Latitude'], list_data[c]['Longitude']): if math.isnan(lat) or math.isnan(lon): pass else: location.append([lat, lon]) HeatMap(location, radius=16).add_to(heat_map) heat_map.save(f'heatMap_{"Spain" if _only_spain else "Global"}.html') logging.info('Heat map successfully generated in html') except Exception as err: logging.error( f'ERROR in generate_heat_map at line {sys.exc_info()[2].tb_lineno}: \n ' f'{err} \n ' f'{list_data[c]}')
def plotNOAADataset(df): """" PLots the heat map of NOAA dataset""" m = folium.Map(zoom_start=10, tiles='cartodbpositron') HeatMap(data=df[['lat', 'lon', 'prcp']].groupby(['lat', 'lon']).sum().reset_index().values.tolist(), radius=8, max_zoom=13).add_to(m) m.save("NOAA Heatmap.html")
def makeHeatmapMap(coordinates): from folium.plugins import HeatMap meanlat = np.mean(coordinates['latitude']) meanlon = np.mean(coordinates['longitude']) # initialize map mapa = folium.Map(location=[meanlat, meanlon], tiles='Cartodb Positron', zoom_start=10) #tiles='OpenStreetMap' coordinatesFinal = [] if len(coordinates) > 1090: #max len is 1090 for the Heat Map for i in range(1090): coordinate = [] coordinate.append(coordinates["latitude"][i]) coordinate.append(coordinates["longitude"][i]) coordinatesFinal.append(coordinate) else: for i in range(len(coordinates)): coordinate = [] coordinate.append(coordinates["latitude"][i]) coordinate.append(coordinates["longitude"][i]) coordinatesFinal.append(coordinate) # convert list of lists to list of tuples coordinatesFinal = [tuple([i[0], i[1]]) for i in coordinatesFinal] # add heat mapa.add_child(HeatMap(coordinatesFinal)) # mapa.add_child(HeatMap((tuple([coordinates['latitude'][i],coordinates['longitude'][i]])))) return mapa.save( "/Users/selinerguncu/Desktop/PythonProjects/Fun Projects/Yelp/yelp/static/foliumHeatmap.html" )
def createMap(cars): cars.rename(columns={'Lat':'latitude','Long':'longitude'}, inplace=True) cars.latitude.fillna(0, inplace = True) cars.longitude.fillna(0, inplace = True) CarMap=folium.Map(location=[39,35],zoom_start=6) HeatMap(data=cars, radius=16).add_to(CarMap) CarMap.save('templates/index.html')
def heat_map(self): if 'coordinates' not in self.dataframe: print("No coordinates in dataframe, add them first with LocationService") heat_map = folium.Map(location=[0, 0], zoom_start=2) points = self.dataframe.dropna().coordinates.tolist() HeatMap(points).add_to(heat_map) return heat_map
def test_heatmap_data(): data = HeatMap(np.array([[3, 4, 1], [5, 6, 1], [7, 8, 0.5]])).data assert isinstance(data, list) assert len(data) == 3 for i in range(len(data)): assert isinstance(data[i], list) assert len(data[i]) == 3
def generateMap(self, tiles, map_zoom_start=6, heatmap_radius=7, heatmap_blur=4, heatmap_min_opacity=0.2, heatmap_max_zoom=4): map_data = [(coords[0], coords[1], magnitude) for coords, magnitude in self.coordinates.items()] # Generate map m = folium.Map(location=self.max_coordinates, zoom_start=map_zoom_start, tiles=tiles, attr=self.getMapCopyright(tiles)) # Generate heat map heatmap = HeatMap(map_data, max_val=self.max_magnitude, min_opacity=heatmap_min_opacity, radius=heatmap_radius, blur=heatmap_blur, max_zoom=heatmap_max_zoom) m.add_child(heatmap) return m
def price_proximity(): boliga = pd.read_csv('./data/boliga_zealand.csv').drop( ['Index', '_1', 'Unnamed: 0'], axis=1) zip_df = pd.DataFrame(boliga['zip_code'].str.split(' ', 1).tolist(), columns=['zip', 'city']) boliga = boliga.assign(zip_int=zip_df['zip']) boliga['zip_int'] = pd.to_numeric(boliga['zip_int'], errors='coerce') boliga = boliga[boliga['zip_int'] <= 2999] heatmap_df = boliga[['lon', 'lat', 'price']].dropna() boliga_map = folium.Map(location=[55.676098, 12.568337], zoom_start=11) folium.Marker(location=[55.676098, 12.568337], icon=folium.Icon(color='red', icon='home')).add_to(boliga_map) heat_data = [(e.lat, e.lon, float(e.price)) for e in heatmap_df.itertuples()] HeatMap(heat_data, radius=7).add_to(boliga_map) boliga_map.save('heatmap.html')
def drawForHeavyPuff(gas_df,iC,zoom,map=None): leakageLat, leakageLong, downwind_latitude, downwind_longitude, map_osm=process_common_data(gas_df,zoom,map) downwind_latitude=gas_df['x_lat'].tolist() radius=gas_df['b'].tolist() time = gas_df['t'].tolist() concentration = gas_df['cmax'].tolist() x_axis=[] x_axis.append([leakageLat, leakageLong,iC]) #draw_circles(leakageLat, leakageLong, f, '#ee6531', 'time ' + str(0) + ' s', '#ee6531', 1, map_osm) for i,xLat,xLong, radius_val,t,c in zip(count(), downwind_latitude,downwind_longitude, radius,time,concentration): opacity=2/(i+1) opacity = c/10 # print "Drawing" # print yLat, yLong, radius_val if (map == None): draw_circles(xLat,xLong,radius_val,'#ee6531','concentration ' + str(c) + ' at time ' + str(t) + ' s','#ee6531',opacity,map_osm) else: draw_circles(xLat, xLong, radius_val, '#3186cc', 'concentration ' + str(c) + ' at time ' + str(t) + ' s', '#3186cc', c, map_osm) x_axis.append([xLat, xLong,c]) #folium.PolyLine(x_axis, color="#0e0d0c", weight=8, opacity=1).add_to(map_osm) HeatMap(x_axis,10).add_to(map_osm) map_osm.save('heavy_puff.html') #print type(map_osm) return map_osm
def make_heatmap(locations, filename='heatmap.html', overlay=''): startingLocation = [49.006239, 8.411572] hmap = folium.Map(location=startingLocation, zoom_start=14) # Creates a heatmap element hm_wide = HeatMap(locations, min_opacity=.5, radius=21, blur=25) # Adds the heatmap element to the map hmap.add_child(hm_wide) # Saves the map to heatmap.hmtl hmap.save(filename) hti = Html2Image() png_file = hti.screenshot(url=filename, save_as=os.path.basename(filename) + '.png')[0] shutil.move(png_file, filename + '.png') img = Image.open(filename + '.png') draw = ImageDraw.Draw(img) # font = ImageFont.truetype(<font-file>, <font-size>) font = ImageFont.truetype( "C:/Users/Simon/AppData/Local/Microsoft/Windows/Fonts/TTNorms-Bold.otf", 100) # draw.text((x, y),"Sample Text",(r,g,b)) draw.text((1400, 0), overlay, (0, 0, 0), font=font, align='right') img = img.resize([int(x * 0.5) for x in img.size]) img.save(filename + '.png') return img
def displayMap(map, decision): blur = st.checkbox("Blur") large = st.checkbox("Large Points") add = 0 if large: add = 6 if blur: b = 15 rad = 20 + add else: b = 1 rad = 4 + add if(decision == 'avg'): minMap = map[['TAVG', 'latitude', 'longitude', 'station', 'state']].groupby(['station', 'latitude','longitude', 'state']).min().reset_index() maxMap = map[['TAVG', 'latitude', 'longitude', 'station', 'state']].groupby(['station', 'latitude','longitude', 'state']).max().reset_index() map = map[['TAVG', 'latitude', 'longitude', 'station', 'state']].groupby(['station', 'latitude','longitude', 'state']).mean().reset_index() map['avg'] = maxMap['TAVG'] - minMap['TAVG'] else: map = map[[decision, 'latitude', 'longitude', 'station', 'state']].groupby(['station', 'latitude','longitude', 'state']).mean().reset_index() max_amount = float(map[decision].max()) hmap = folium.Map(location=[40, -100], zoom_start=4) hm_wide = HeatMap(list(zip(map['latitude'].values, map['longitude'].values, map[decision].values)), min_opacity=0, max_val=max_amount, radius=rad, blur=b, max_zoom=5, control_scale = True) hmap.add_child(hm_wide) folium_static(hmap) graph = st.checkbox('Show Graph') if graph: showGraph(map, decision)
def folium_map(df, table, variable, unit): df.dropna(subset=[variable], inplace=True) df.reset_index(drop=True, inplace=True) normalized = normalize(df[variable]) data = list(zip(df.lat, df.lon, normalized)) m = folium.Map([df.lat.mean(), df.lon.mean()], tiles=None, zoom_start=3, control_scale=True, prefer_canvas=True) m.get_root().title = 'Map: ' + variable + unit m = addLayers(m) HeatMap(data, name='Data Density (%s)' % variable).add_to(m) m = addMarkers(m, df, variable, unit) m = addMousePosition(m) folium.LayerControl(collapsed=True).add_to(m) # m = addFullScreen(m) figureDir = get_figure_dir() if not os.path.exists(figureDir): os.makedirs(figureDir) fname = figureDir + 'heatMap.html' if os.path.exists(fname): os.remove(fname) m.save(fname) open_HTML(fname) return
def draw_heat_map(dataset): base_map = generateBaseMap() HeatMap(data=dataset[['lat', 'long', 'AV_TOTAL']]. groupby(['lat', 'long']).mean(). reset_index().values.tolist(), radius = 8, max_zoom = 13).add_to(base_map) base_map.save('heatmap.html')
def heatmap_features_by_loc(data, feature): """ Generates a heatmap based on lat, long and a feature :param data: dataset :param feature: feature name :return: """ max_value = data[feature].max() lat = np.array(data.lat, dtype=pd.Series) lon = np.array(data.long, dtype=pd.Series) mag = np.array(data[feature], dtype=pd.Series) / max_value d = np.dstack((lat, lon, mag))[0] heatmap_data = [i for i in d.tolist()] hmap = folium.Map(location=[47.55, -122.0], zoom_start=10, tiles='stamentoner') hm_wide = HeatMap(heatmap_data, min_opacity=0.7, max_val=max_value, radius=1, blur=1, max_zoom=1, ) hmap.add_child(hm_wide) return hmap
def view_entire_location(map_data): ''' Create a map that shows all the locations available in the data ''' assert isinstance(map_data, pd.DataFrame), "map_data not a data frame" # define the world map world_map = folium.Map() # San Diego Latitude and Longitude latitude = 32.72 longitude = -117.16 limit = 10000 data = map_data.iloc[0:limit, :] san_map = folium.Map(location=[latitude, longitude], zoom_start=10) HeatMap(data[['latitude','longitude']].dropna(),radius=8,gradient={0.2:'blue',0.4:'purple',0.6:'orange',1.0:'red'}).add_to(san_map) san_map # Same figure above with markers token = 'pk.eyJ1IjoiNzM2ODkxNDEwIiwiYSI6ImNrbDY4MnlvZzBibGMyd283OGprYWFuM3UifQ.MqFaTEXVYsnkkwFhxwEkmQ' fig = go.Figure(go.Scattermapbox(mode='markers', lon = data.longitude, lat = data.latitude, hovertext = data.id)) fig.update_layout(mapbox={'accesstoken' : token, 'center' : {'lon' : -117.063, 'lat': 32.765}, 'zoom':10.0}, margin = {'l' : 0, 'r' : 0, 't' : 0, 'b' : 0}) return data,token