# def generateBaseMap(default_location=[45.7372756, 4.8175837], default_zoom_start=12): # base_map = folium.Map(location=default_location, control_scale=True, zoom_start=default_zoom_start) # return base_map # base_map = generateBaseMap() # HeatMapWithTime(locationlist).add_to(base_map) # base_map.save('L.html') #HeatMap def generateBaseMap(default_location=[45.7372756, 4.8175837], default_zoom_start=12): base_map = folium.Map(location=default_location, control_scale=True, zoom_start=default_zoom_start) return base_map base_map = generateBaseMap() HeatMap(data=data[['latitude', 'longitude']], gradient={0.2: 'blue', 0.4: 'lime', 0.6: 'orange', 0.8: 'yellow', 1: 'red'}, radius=15, max_zoom=18).add_to(base_map) base_map.save('M.html') ###Marker Cluster # map2 = folium.Map(location=[45.7372756, 4.8175837], tiles='CartoDB dark_matter', zoom_start=11) # marker_cluster = folium.plugins.MarkerCluster().add_to(map2) # for point in range(0, len(locationlist)): # folium.Marker(locationlist[point], popup=price[point]).add_to(marker_cluster) # map2.save('carte4.html')
# # A good blog post on Kaggle about Folium can also be found here: # https://www.kaggle.com/daveianhickey/how-to-folium-for-maps-heatmaps-time-data m = folium.Map() # m ## Adding markers to map # Convert to list of lat,long, name tuples markers = list(zip(latitudes, longitudes, names, WebPageAddress)) markers = np.array(markers) markers # `i[:2]` slices first two elements of list which for `markers` # is latitude and longitude for i in markers: coords = i[:2] title = i[2] webaddress = i[3] #folium.Marker(location=coords, popup=title).add_to(m) folium.Marker(location=coords, popup=(title,webaddress)).add_to(m) # m ## Adding heatmap layer HeatMap(markers[:,:2]).add_to(m) m ## Ports Heatmap
import folium from folium.plugins import HeatMap import pandas as pd ##Dados da Plataforma Brasil.io dados_covid19 = pd.read_csv( 'https://raw.githubusercontent.com/wcota/covid19br/master/cases-gps.csv') mapa = folium.Map(location=[-15.77972, -47.92972], zoom_start=4, min_zoom=4, control_scale=True) locais = dados_covid19[["lat", "lon"]].values.tolist() HeatMap(locais, radius=13).add_to(mapa) mapa.save('mapa.html')
x = np.array(df[['longitude','latitude', 'mag']], dtype='float64') plt.scatter(x[:,0], x[:,1], alpha=0.2, s= 50) plt.show() m = folium.Map(location=[df.latitude.mean(), df.longitude.mean()], zoom_start=5) for _, row in df.iterrows(): if row.mag >= 5: folium.CircleMarker( location=[row.latitude, row.longitude], radius=5, popup=re.sub(r'[^a-zA-Z]+', '', row.time), color='#FE1A16', fill=True, fill_colour='#FE1A16' ).add_to(m) else: folium.CircleMarker( location=[row.latitude, row.longitude], radius=5, popup=re.sub(r'[^a-zA-Z]+', '', row.time), color='#ffbd87', fill=True, fill_colour='#ffbd87' ).add_to(m) m.save("scattered_plot.png") im = Image.open("scattered_plot.png") im.show() m1=folium.Map(location=[df.latitude.mean(), df.longitude.mean()], zoom_start=5) HeatMap(data=df[['latitude', 'longitude', 'mag']].groupby(['latitude', 'longitude']).sum().reset_index().values.tolist(), radius=8, max_zoom=13).add_to(m1) m1.save("HeatMap.png") im1 = Image.open("scattered_plot.png") im1.show()
YY=np.array(Y) z = list(zip(YY,XX)) zz=np.array(z) print(zz)from sklearn.cluster import KMeans y_pred = KMeans(n_clusters=3, random_state=9).fit_predict(zz) plt.scatter(zz[:, 0], zz[:, 1], c=y_pred) plt.show()schools_map = folium.Map(location=[gdf['latitude'].mean(), gdf['longitude'].mean()], zoom_start=10) marker_cluster = plugins.MarkerCluster().add_to(schools_map) tupxy = [tuple(x) for x in gdf[["latitude", "longitude"]].values] for coord in tupxy: folium.CircleMarker(location=[coord[0], coord[1]],radius=5,color='#3186cc',fill_color='#3186cc',).add_to(schools_map) file_path = r"test2.html" schools_map.save(file_path)# from folium.plugins import HeatMap data = gdf[["latitude", "longitude"]].values.tolist() hmap = folium.Map(location=[gdf['latitude'].mean(), gdf['longitude'].mean()],control_scale=True, zoom_start=12) hmap.add_child(HeatMap(data, radius=5, gradient={.2: 'blue', .35: 'lime', .6: 'yellow'})) file_path = r"test_heatmap.html" hmap.save(file_path)gdf_chi = gdf[gdf['venueCategory'] == 'Chinese Restaurant'] gdf_chiChinese_map = folium.Map(location=[gdf_chi['latitude'].mean(), gdf_chi['longitude'].mean()], zoom_start=12) tupxy = [tuple(x) for x in gdf_chi[["latitude", "longitude"]].values] for coord in tupxy: folium.CircleMarker(location=[coord[0], coord[1]],radius=5,color='#3186cc',fill= True, fill_color='#3186cc',).add_to(Chinese_map) file_path = r"test_chi.html" Chinese_mapdata = gdf_chi[["latitude", "longitude"]].values.tolist() hmap = folium.Map(location=[gdf_chi['latitude'].mean(), gdf_chi['longitude'].mean()],control_scale=True, zoom_start=13) hmap.add_child(HeatMap(data, radius=5, gradient={.1: 'blue', .2: 'lime', .3: 'yellow'})) file_path = r"test_chi_heatmap.html" hmapcluster_map = folium.Map(location=[gdf['latitude'].mean(), gdf['longitude'].mean()], zoom_start=10) # create a mark cluster object marker_cluster = plugins.MarkerCluster().add_to(cluster_map)
hints = sum(moments[6:12]) elif PERIOD == 'afternoon': hints = sum(moments[12:18]) elif PERIOD == 'evening': hints = sum(moments[18:22]) else: hints = moments[23] + sum(moments[0:6]) return ceil(hints / 40) def place_hints_per_hour(place, hour): moments = json.loads(place[WEEK_DAY]) hints = moments[hour] return ceil(hints / 40) natal = folium.Map(location=[-5.8313086, -35.2047059], zoom_start=13) places = pd.read_csv('data/places_cleaned.csv') heat_dots = [] for index, row in places.iterrows(): place_dots = place_hints_per_hour(row, 7) * [[row.lat, row.lng]] heat_dots += place_dots # folium.CircleMarker([row.lat, row.lng], popup=row.place_name, radius=2).add_to(natal) HeatMap(heat_dots).add_to(natal) natal.save('natal.html')
def reponseQuestion2(): # Create connexion cluster = Cluster(["localhost"]) session = cluster.connect(KEYSPACE) # User input instant = input("\nDonnez un instant (par example 2014-6-15 12:55) : ") qury = f'''SELECT station, lon, lat, tmp, relh, drct, sknt, vsby FROM asos2 WHERE time='{instant}';''' result = session.execute(qury) map_data = pd.DataFrame() for row in result: map_data = map_data.append([[element for element in row]], ignore_index=True) map_data.columns=['station','lon','lat','temperature','relative_humidity','wind_direction','wind_speed','visibility'] # Create point map weather_map = folium.Map(location=[42, 13], zoom_start=6) for i in range(len(map_data)): # Define popup popup_text = folium.Html( '<b>Temps d\'observation : {}</b></br> <b>Station : {}</b></br> <b>lon : {}</b></br> <b>lat : {}</b></br> <b>Température (fahrenheit) : {}</b></br> \ <b>Humidité relative (%) : {}</b></br> <b>Direction du vent : {}</b></br> <b>Vitesse du vent (mille marin) : {}</b></br> <b>Visibilité (mile) : {}</b></br>'\ .format(instant, map_data.iloc[i]['station'], round(map_data.iloc[i]['lon'],2), round(map_data.iloc[i]['lat'],2), round(map_data.iloc[i]['temperature'],2), round(map_data.iloc[i]['relative_humidity'],2), map_data.iloc[i]['wind_direction'], map_data.iloc[i]['wind_speed'], round(map_data.iloc[i]['visibility'],2)), script=True) map_popup = folium.Popup(popup_text, max_width=2650) # Add points to the map folium.Marker([map_data.iloc[i]['lat'], map_data.iloc[i]['lon']], popup=map_popup).add_to(weather_map) # Save map weather_map.save(f'''images/Meteo_carte_{instant}.html''') # Create heat map lats = np.array(map_data['lat'][0:len(map_data)]) lons = np.array(map_data['lon'][0:len(map_data)]) tmps = np.array(map_data['temperature'][0:len(map_data)]) heat_data = [[lats[i],lons[i],tmps[i]] for i in range(len(map_data))] heat_map = folium.Map(location=[42, 13], zoom_start=6) HeatMap(heat_data).add_to(heat_map) for i in range(len(map_data)): # Define popup popup_text = folium.Html( '<b>Station : {}</b></br> <b>lon : {}</b></br> <b>lat : {}</b></br> <b>Température (fahrenheit) : {}</b>'\ .format(map_data.iloc[i]['station'], round(map_data.iloc[i]['lon'],2), round(map_data.iloc[i]['lat'],2), round(map_data.iloc[i]['temperature'],2)), script=True) map_popup = folium.Popup(popup_text, max_width=2650) # Add points to the map folium.Marker([map_data.iloc[i]['lat'], map_data.iloc[i]['lon']], popup=map_popup).add_to(heat_map) heat_map.save(f'''images/Carte_de_chaleur_{instant}.html''') print(""" *** Cartes creees avec succes ! ***\n ==================\n""")
def heat_map(df): locs = zip(df.lon, df.lat) m = folium.Map([22.3511148, 78.6677428], tiles='stamentoner', zoom_start=5) HeatMap(locs).add_to(m) return st.markdown(m._repr_html_(), unsafe_allow_html=True)
# print(MAES) print(sum([float(i) for i in MAES])) print('RSME Average : ') print(sum([float(i) for i in RSMES])) # part 3 df = pd.read_csv('boliga_zealand.csv').drop(['Index', '_1', 'Unnamed: 0'], axis=1) df = df[['lat', 'lon', 'price']].dropna() norreport = (55.6836329, 12.5709413) my_map = folium.Map(location=[55.6836329, 12.5709413], zoom_start=10) folium.Marker(location=norreport, icon=folium.Icon(color='red', icon='home')).add_to(my_map) data = [] for row in df.itertuples(): data.append([row.lat, row.lon, row.price]) HeatMap(data, radius=7).add_to(my_map) my_map.save('heatmap.html') # According to the map data we see as the best the triangle area between Bronshøj, Islev and Vanløse. Not only that # the HeatMap shows that as a reasonably priced area (however we do not consider the size of the apartments, so it # could be that the apartments are just smaller in the area) but also the distance and connection to the city center # is pretty good, especially around Vanløse where is also metro. # Part 4: Housing price model def haversine_distance(lat_dest, lon_dest): lat_orig, lon_orig = (55.6836722, 12.5693963) # lat_dest, lon_dest = destination radius = 6371
from datawrangling.geomunging import g2 from pprint import pprint from folium import LayerControl, Map, FeatureGroup from folium.plugins import HeatMap # create map object m = Map(tiles='openstreetmap',min_zoom=7, max_zoom=17, zoom_start=7,\ min_lat=40, max_lat=48,min_lon=-114, max_lon=-128, \ max_bounds=True) fg = FeatureGroup('Heat Map') # add list of coordinates to map object fg.add_child(HeatMap(list(zip(g2.lat.values, g2.lon.values)))) m.add_child(fg) LayerControl().add_to(m) m.save(r'templates\g2eventheat.html')
us_map = folium.Map(location=[40, -99], zoom_start=4) # Ensure you're handing it floats ufo['latitude'] = ufo['latitude'].astype(float) ufo['longitude'] = ufo['longitude'].astype(float) heat_df = ufo[['latitude', 'longitude']] heat_df = heat_df.dropna(axis=0, subset=['latitude', 'longitude']) # List comprehension to make out list of lists heat_data = [[row['latitude'], row['longitude']] for index, row in heat_df.iterrows()] # Plot it on the map HeatMap(heat_data).add_to(us_map) # Display the map us_map #us_map.save('ufoheatmap.html') sns.catplot(y=ufo["shape"], kind="count", palette="viridis", edgecolor=".6", data=ufo.sort_values("shape")) ufo.loc[ufo['shape'] == 'rectangle', 'shape'] = 'geometric' ufo.loc[ufo['shape'] == 'chevron', 'shape'] = 'geometric' ufo.loc[ufo['shape'] == 'triangle', 'shape'] = 'geometric' ufo.loc[ufo['shape'] == 'diamond', 'shape'] = 'geometric'
print(accuracy) # plotting the results import pandas as pd import folium from folium.plugins import HeatMap for_map = pd.read_csv('/home/cmlare/Data/RF Data/Processed/2018-05-08 to 2018-05-15_integrated_classified.csv') for_map max_amount = float(for_map['TSL_MIN'].max()) max_amount hmap = folium.Map(location=[6.917200, 79.913300], zoom_start=7, ) hm_wide = HeatMap( list(zip(for_map.XEnd.values, for_map.YEnd.values, for_map.TSL_MIN.values)), min_opacity=0.8, max_val=max_amount, radius=17, blur=15, max_zoom=1, ) # folium.GeoJson(district23).add_to(hmap) hmap.add_child(hm_wide)
# subset = data[(data.GETON_DATE >= begin) & (data.GETON_DATE <= end)] # subset = subset[(subset.GETON_LONGITUDE >= 118.05) & (subset.GETON_LATITUDE >= 24.44)] # subset = subset.sample(frac=0.25, random_state=99) # x = list(subset.GETON_LONGITUDE) # y = list(subset.GETON_LATITUDE) od = pd.read_csv('data/od_temp.csv') x = list(od.DEP_LONGITUDE) y = list(od.DEP_LATITUDE) x = np.asarray(x).reshape((len(x), 1)) y = np.asarray(y).reshape((len(y), 1)) X = np.hstack((x, y)) for i in range(len(X)): X[i][0], X[i][1] = wgs2gcj(X[i][0], X[i][1]) X1 = np.hstack((y, x)) for i in range(len(X1)): X1[i][1], X1[i][0] = wgs2gcj(X1[i][1], X1[i][0]) band = getBandWidth(X) print('Band Width:' + str(band)) kde = KernelDensity(bandwidth=band, kernel='epanechnikov').fit(X) res = kde.score_samples(X) res = np.asarray(res).reshape((len(res), 1)) kde_y = np.hstack((X1, res)) xmmap = folium.Map( location=(24.45, 118.08), zoom_start=13, max_zoom=14, tiles= 'http://wprd02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7', attr='Powered by Amap ©️2020 高德软件 GS(2019)6379号 - 甲测资字11002004') HeatMap(kde_y).add_to(xmmap) xmmap.save('out/passengerkde.html')
distances = stations.geometry.distance(recent_release.geometry) distances print('Mean distance to monitoring stations: {} feet'.format(distances.mean())) print('Closest monitoring station ({} feet):'.format(distances.min())) print(stations.iloc[distances.idxmin()][["ADDRESS", "LATITUDE", "LONGITUDE"]]) # Buffer - to understand all points on a map are within what radius away from a point two_mile_buffer = stations.geometry.buffer(2 * 5280) two_mile_buffer.head() # Create map with release incidents and monitoring stations m = folium.Map(location=[39.9526, -75.1652], zoom_start=11) HeatMap(data=releases[['LATITUDE', 'LONGITUDE']], radius=15).add_to(m) for idx, row in stations.iterrows(): Marker([row['LATITUDE'], row['LONGITUDE']]).add_to(m) # Plot each polygon on the map GeoJson(two_mile_buffer.to_crs(epsg=4326)).add_to(m) # Show the map m # Turn group of polygons into single multipolygon my_union = two_mile_buffer.geometry.unary_union print('Type:', type(my_union)) # Show the MultiPolygon object my_union
(0.0021852 * (abs(data.iloc[i]['lon']))) + 1) * 50000, color=colorgradient[counter], fill=True, fill_color=colorgradient[counter], blur=15, # max_zoom=1, min_opacity=0.8).add_to(m) counter += 1 data_list = list(zip(data.lon.values, data.lat.values, data.value.values)) max_amount = float(data['value'].max()) print(max_amount) hm_wide = HeatMap( data_list, min_opacity=0.2, max_val=max_amount, radius=10, blur=15, max_zoom=1, ) h.add_child(hm_wide) h.save('heatmap.html') # for i in range(0, len(data)): # colors = colorgradient # folium.Circle( # location=[data.iloc[i]['lon'], data.iloc[i]['lat']], # popup=(data.iloc[i]['name']), # #radius=data.iloc[i]['value'] * 100000, # radius= (2)* # ((-(0.0000992*(abs(data.iloc[i]['lon']**2))))-(0.0021852*(abs(data.iloc[i]['lon'])))+1) # * 50000,
import seaborn as sns import folium #import webbrowser from folium.plugins import HeatMap #posi=pd.read_excel("2015Cities-CHINA.xlsx") posi = pd.read_excel("2015Cities-CHINA_4.xlsx") num = 130 lat = np.array(posi["lat"][0:num]) # 获取维度之纬度值 lon = np.array(posi["lon"][0:num]) # 获取经度值 pop = np.array(posi["pop"][0:num], dtype=float) # 获取人口数,转化为numpy浮点型 gdp = np.array(posi["GDP"][0:num], dtype=float) # 获取数,gdp转化为numpy浮点型 gdp_ave = np.array(posi["GDP_Average"][0:num] / 10, dtype=float) # 获取数,平均gdp转化为numpy浮点型 print(posi["GDP_Average"][0:num]) #exit(0) #data1 = [[lat[i],lon[i],pop[i]] for i in range(num)] #将数据制作成[lats,lons,population]的形式 #data1 = [[lat[i],lon[i],gdp[i]] for i in range(num)] #将数据制作成[lats,lons,gdp]的形式 data1 = [[lat[i], lon[i], gdp_ave[i]] for i in range(num)] #将数据制作成[lats,lons,gdp_ave]的形式 map_generate = folium.Map(location=[35, 110], zoom_start=5) #绘制Map,开始缩放程度是5倍 HeatMap(data1).add_to(map_generate) # 将热力图添加到前面建立的map里 #file_path = r"/Users/fuchuang/Downloads/polulation.html" file_path = r"/Users/fuchuang/Downloads/gdp_average.html" map_generate.save(file_path) # 保存为html文件
rest_loc.columns = ['Name', 'count'] restaurant_locations = rest_loc.merge(locations, on='Name').dropna() restaurant_locations # In[46]: import folium from folium.plugins import HeatMap # In[47]: basemap = folium.Map(location=[12.97, 77.59]) # In[48]: HeatMap(data=restaurant_locations[['latitude', 'longitude', 'count']]).add_to( basemap) # In[49]: basemap # In[50]: import wordcloud # In[51]: from wordcloud import WordCloud, STOPWORDS # In[52]:
import numpy as np import pandas as pd import seaborn as sns import folium import webbrowser from folium.plugins import HeatMap posi = pd.read_excel("2015Cities-CHINA.xlsx") num = 100 lat = np.array(posi["lat"][0:num]) # 获取维度之维度值 lon = np.array(posi["lon"][0:num]) # 获取经度值 pop = np.array(posi["pop"][0:num], dtype=float) # 获取人口数,转化为numpy浮点型 gdp = np.array(posi["GDP"][0:num], dtype=float) # 获取人口数,转化为numpy浮点型 data1 = [[lat[i], lon[i], pop[i]] for i in range(num)] #将数据制作成[lats,lons,weights]的形式 map_osm = folium.Map(location=[35, 110], zoom_start=4) #绘制Map,开始缩放程度是5倍 HeatMap(data1).add_to(map_osm) # 将热力图添加到前面建立的map里 file_path = "map5.html" map_osm.save(file_path) # 保存为html文件 webbrowser.open(file_path) # 默认浏览器打开
import numpy as np import pandas as pd import folium from folium import plugins from folium.plugins import HeatMap # read a csv file into a dataframe df_acc = pd.read_csv('Chicago_Crimes_2012_to_2017.csv', dtype=object) df_acc['Latitude'] = df_acc['Latitude'].astype(float) df_acc['Longitude'] = df_acc['Longitude'].astype(float) my_map = folium.Map(location=[41.881832, -87.623177], zoom_start=10) heat_df = df_acc[['Latitude', 'Longitude']] heat_df = heat_df.dropna(axis=0, subset=['Latitude', 'Longitude']) heat_data = [[row['Latitude'], row['Longitude']] for index, row in heat_df.iterrows()] # create heatmap based on the coordiates in the data frame HeatMap(heat_data, radius=5, blur=10, max_val=1, min_opacity=0.5).add_to(my_map) my_map.save('chicagoMKcluster.html')
from sklearn.metrics import r2_score # ## 因子分析 # In[54]: # 经纬度 import folium from folium.plugins import HeatMap geo_center = [24.5580803, 118.0747703] geo_map = folium.Map(location=geo_center, zoom_start=13.5) heatdata = ori_df[['纬度', '经度', '单价']].values.tolist() HeatMap(heatdata, radius=7).add_to(geo_map) # gradient={.4:'blue',.65:'yellow',1:'red'} geo_map # ### 从重要性分析可看出,经纬度分布是影响房价的最主要因素,即“地段”为影响房价的强因子 # ### 通过房价地理热图,可发现:高房价房源主要分布在思明区及湖里区,并且处在厦门市中心区域,其中房价最高的区域落在湖里区“厦门市软件园”地带 # ### 另外,集美区及海沧区高房价区有着沿海、靠近市中心等特点 # In[76]: # 年份与房价分布关系 ori_df.sort_values(by='年份', ascending=True, inplace=True) plt.figure(figsize=(18, 9)) cmap = sns.cubehelix_palette(rot=-.2, as_cmap=True) fig = sns.scatterplot(x="年份", y="单价",
! pip install folium -t "/tmp" > /dev/null 2>&1 import pandas as pd import folium from folium.plugins import HeatMap ds = datasets[0] ds = ds.fillna(0) #Assign Map Attributes m = folium.Map(location=[37.700, -122.39], title="Geographic Sales", height=500, center_lat=37.700, center_lng=-122.39, dot_size=.001, dot_opacity=.9,) # Conver lat and lon to numpy array (old method: .as_matrix()) points_array = ds[['lat', 'lng']].values HeatMap(points_array, min_opacity=0.3, radius=20).add_to(m) m
# heat_df = df_acc[['Latitude', 'Longitude']] # heat_df = heat_df.dropna(axis=0, subset=['Latitude','Longitude']) # heat_data = [[row['Latitude'],row['Longitude']] for index, row in heat_df.iterrows()] # #print(heat_data) # read a csv file of chicago crimes fd = open('Chicago_Crimes_2012_to_2017.csv', 'r') csvReader = csv.reader(fd, delimiter=',') next(csvReader) # create two lists recording all the coordinates of day and night heat_data_day = [] heat_data_night = [] for row in csvReader: if(row[20] != "" and row[21] != ""): lat = float(row[20]) lon = float(row[21]) if(selectDay(row[3])): heat_data_day.append([lat,lon]) else: heat_data_night.append([lat,lon]) fd.close() HeatMap(heat_data_day, radius = 12, blur = 18, max_val = 20, min_opacity = 0.5).add_to(my_map_day) HeatMap(heat_data_night, radius = 12, blur = 18, max_val = 20, min_opacity = 0.5).add_to(my_map_night) # save the files as html my_map_day.save('visualization/heatmapDaytime.html') my_map_night.save('visualization/heatmapNight.html')
def test_heat_map_exception(): with pytest.raises(ValueError): HeatMap(np.array([[4, 5, 1], [3, 6, np.nan]])) with pytest.raises(Exception): HeatMap(np.array([3, 4, 5]))
# # Viewing the Districts that have the Highest Crime Rates # In[22]: crime = df.groupby(['DISTRICT', 'STREET', 'REPORTING_AREA', 'Lat', 'Long']).sum().reset_index() # In[24]: crime.update(crime['DISTRICT'].map('District:{}'.format)) crime.update(crime['REPORTING_AREA'].map('Reports:{}'.format)) # In[25]: m2 = folium.Map(location=boston, tiles='stamentoner', zoom_start=13) HeatMap(data=crime[['Lat', 'Long']], radius=15).add_to(m2) # marking crime scenes def plotDot(point): folium.CircleMarker(location=[point.Lat, point.Long], radius=5, weight=2, popup=[point.DISTRICT, point.REPORTING_AREA], fill_color='#000000').add_to(m2) crime.apply(plotDot, axis=1) m2.fit_bounds(m2.get_bounds()) m2
import pandas as pd import matplotlib.pyplot as plt #%matplotlib inline df1=pd.read_csv("school.csv") def generateBaseMap(default_location=[28.4595, 77.0266], default_zoom_start=12): base_map = folium.Map(location=default_location, control_scale=True, zoom_start=default_zoom_start) return base_map from folium.plugins import HeatMap df1 = df1[df1['Latitude']>=1].copy() df1['count'] = 1 base_map3 = generateBaseMap() HeatMap(data=df1[['Latitude', 'Longitude', 'count']].groupby(['Latitude', 'Longitude']).sum().reset_index().values.tolist(), radius=8, max_zoom=13).add_to(base_map3)
log = file['log'] # n: entries people number for this stop (All 7 months' summary) n = file['n'] # For loop to merge for j in range(len(lat)): # Child list to store object[lat,log,count] child = [] # Add object into child list child.append(lat[j]) child.append(log[j]) child.append(n[j] / 2100) # Add child list into total data list data.append(child) # Folium itself function to define a map with a view lat/log and map zoom level m = folium.Map([42.3, -71.1], tiles='stamentoner', zoom_start=11) # Add all the point data into map function HeatMap(data).add_to(m) mkdir('/Users/Eddy/Desktop/Python_MBTA/Step4_heatmap/') # Save the created map into a html file m.save('/Users/Eddy/Desktop/Python_MBTA/Step4_heatmap/heatmap' + str(i % 24) + '_' + str((i + 2) % 24) + '.html')
map[d] = map[d] + 1 else: map[d] = 1 print(len(map.keys())) loc_count = list() def parse_key(map): for key in map.keys(): temp = list() temp_key = key.split(sep=" ") lon = float(temp_key[1]) lat = float(temp_key[-1].split("]")[0]) temp.append(lon) temp.append(lat) temp.append(map[key]) loc_count.append(temp) return loc_count loc_count = parse_key(map) loc_count = np.array(loc_count) print(np.mean(loc_count, axis=0)) import pandas as pd import folium from folium.plugins import HeatMap map_osm = folium.Map(location=[31.14, 121.5], zoom_start=5) #绘制Map,开始缩放程度是5倍 HeatMap(loc_count).add_to(map_osm) # 将热力图添加到前面建立的map里 file_path = r"./people.html" map_osm.save(file_path) # 保存为html文件
import pandas as pd import folium import os import sys from folium.plugins import HeatMap # Read map data from CSV map_data = pd.read_csv("world.csv") # Find highest purchase amount max_amount = float(map_data['s'].max()) # Makes a new map centered on the given location and zoom startingLocation = [30, 35] # EDIT THIS WITH YOUR CITIES GPS COORDINATES! hmap = folium.Map(location=startingLocation, zoom_start=7) # Creates a heatmap element hm_wide = HeatMap( list(zip(map_data.lat.values, map_data.lon.values, map_data.s.values)), min_opacity=0.3, max_val=max_amount, radius=20, blur=15, max_zoom=1) # Adds the heatmap element to the map hmap.add_child(hm_wide) # Saves the map to heatmap.hmtl hmap.save(os.path.join('.', 'heatmap.html'))
folium.GeoJson(data=gj8, style_function=lambda feature:{ 'fillColor': '#D2DD30', 'color': '#5F6500', 'weight': 0.4, } ).add_to(opsp) tree = folium.map.FeatureGroup(name='Trees') dTree=[] for feature in dgj12['features']: if feature['geometry']['type'] == 'Point': loc = feature['geometry']['coordinates'] dTree.append(loc) #npTree=np.array(dTree) HeatMap(data=dTree,radius=15).add_to(tree) '''comers.add_to(folium_map) rdl.add_to(folium_map) plaza.add_to(folium_map) plt.add_to(folium_map) uni.add_to(folium_map) #bft.add_to(folium_map) #sw.add_to(folium_map) mts.add_to(folium_map) bus.add_to(folium_map) bike.add_to(folium_map)''' opsp.add_to(folium_map) tree.add_to(folium_map) folium.LayerControl().add_to(folium_map)
import folium import webbrowser from folium.plugins import HeatMap posi = pd.read_csv( 'DistrictMap.csv') # Get seismic data stored on your computer #print (posi) num = 7 ## assuming to start from 0 so total num+1 data points here lat = np.array(posi['lat'][0:num + 1]) # Get latitude value lon = np.array(posi['lon'][0:num + 1]) # Get longitude value js = np.array(posi['Confirmed'][0:num + 1], dtype=float) # Convert to numpy floating point data #print(js) data1 = [[lat[i], lon[i], js[i]] for i in range(num + 1)] # Specification data format map_osm = folium.Map(location=[23.8103, 90.412], zoom_start=7, tiles='Stamen Terrain', control_scale=True) HeatMap(data1).add_to(map_osm) # Add heat map to the previously created map #print(data1) #map_osm file_path = 'E:\Corona\test2.html' print(data1) map_osm.save(file_path) # Save as html file webbrowser.open(file_path) # Default browser open map_osm