def show_acce(map_data_p, lat0_p, lng0_p, vehicleplate_number_p, num1_p, acceleration_data_p, lat_p, lng_p, location_time_p, file_out_path_p): m = folium.Map([lat0_p, lng0_p], zoom_start=8) m.add_child(folium.LatLngPopup()) #在地图上显示经纬度; route = folium.PolyLine( #polyline方法为将坐标用线段形式连接起来 map_data_p, #将坐标点连接起来 weight=3, #线的大小为3 color='blue', #线的颜色为橙色 opacity=0.8 #线的透明度 ).add_to(m) #将这条线添加到刚才的区域m内 for i in range(num1_p): if i != 0 and i % 59 == 0: y_data = [acceleration_data_p[j] for j in range(i - 59, i + 1, 1)] vis = vincent.Line(y_data, width=320, height=150) vis.axis_titles(x=location_time_p[i - 59] + '至' + location_time_p[i] + '的加速度变化', y='单位:m/s^2') vis_json = vis.to_json() tooltip = location_time_p[i - 59] + '至' + location_time_p[i] status = 0 for k in range(i - 59, i + 1): if acceleration_data_p[k] > 3 or acceleration_data_p[ k] < -3: #判断加速度 status = 1 if status == 1: folium.Marker( location=[lat_p[i], lng_p[i]], popup=folium.Popup(max_width=3250).add_child( folium.Vega(vis_json, width=380, height=200)), icon=folium.Icon(color='red', icon='info-sign'), tooltip=tooltip).add_to( m ) #在每60条记录处显示一个标记点,且点击标记点可以看到过去60条记录内车辆的加速度变化折线图速度变化折线图 else: folium.Marker( location=[lat_p[i], lng_p[i]], popup=folium.Popup(max_width=3250).add_child( folium.Vega(vis_json, width=380, height=200)), tooltip=tooltip).add_to( m ) #在每60条记录处显示一个标记点,且点击标记点可以看到过去的60条记录内车辆的加速度变化折线图速度变化折线图 html_path = os.path.join('r', file_out_path_p, vehicleplate_number_p + '_acceleration.html') m.save(html_path) #将结果以HTML形式保存 webbrowser.open(html_path, new=1)
def make_line_chart_popup(data_row:pd.Series, title:str) -> folium.Popup: '''Create a line chart popup from temporal Series for departements Index of the Series have to be in {year}_median, {year}_decile1, {year}_decile9, {year+1}_median, {year+1}_decile1... format this popup can be added in map layers''' # filter index names and build 3 columns from one(series) data = { 'decile_1': data_row.filter(regex=".*decile_1$").values, 'decile_9': data_row.filter(regex=".*decile_9$").values, 'median': data_row.filter(like="median").values, } df_to_display = pd.DataFrame.from_dict(data) data_row = data_row.drop("color") # create index of the dataframe from the inital data_row Series.index df_to_display.index = pd.to_datetime(list(dict.fromkeys([int(annee_c[:4]) for annee_c in data_row.index.tolist()])), format="%Y") line_chart = vincent.Line(df_to_display, width=300, height=200) line_chart.axis_titles(x='Année', y='prix m2') line_chart.legend(title=title) popup = folium.Popup() folium.Vega(line_chart, width = 400, height=250).add_to(popup) return popup
def map_plot(file): # generate a new map folium_map = folium.Map(location=[43.6532, -79.3832], zoom_start=13, tiles="Stamen Terrain") for index, row in file.iterrows(): #Defining marker colours. if int(row['actual_height']/3) <= int(row['ht_height']/3): color="#4daf4a" else: color="#fc8d62" # Create vincent chart and popup. data = [int(row["ht_height"]/3), int(row["actual_height"]/3),int(row["nearest_neigh"]/3),int(row["rand_forest"]/3)] ind = ['By-law Limit', 'Actual', 'Nearest Buildings', 'Random Forest'] df = pd.DataFrame (data, index = ind) bar_chart = vincent.Bar(df, width=350, height=300) bar_chart.axis_titles (x='', y='Number of Floors') bar_chart.colors(brew='Set3') bar_chart.scales['x'].padding = 0.2 bar_json = bar_chart.to_json() bar_dict = json.loads(bar_json) popup = folium.Popup(max_width=400) folium.Vega(bar_dict, height=350, width=400).add_to(popup) folium.CircleMarker(location=(row["lat"],row["long"]),popup=popup, color=color, radius=5, fill=True ).add_to(folium_map) return folium_map
def visualMap(self): mdCoords = [39.38, -77.36] # Frederick County MD GPS coordinates allScores = self.score2Json() map = folium.Map(location=[mdCoords[0], mdCoords[1]], zoom_start=10, control_scale=True, prefer_canvas=True, disable_3d=True) meanScores = allScores[0] folium.Choropleth(geo_data=self.gdf, name='choropleth', data=meanScores, columns=['School', 'Mean Score'], key_on='feature.properties.School', fill_color='YlGnBu', legend_name='Mean sentiment score', na_fill_color='white', na_fill_opacity=0.2, fill_opacity=0.7, line_weight=0.6, line_opacity=0.2).add_to(map) scores = allScores[1] schools = list(scores.keys()) coords = allScores[2] for school, coord in zip(schools, coords): chart = self.json2PieChart(scores[school], school) vega = folium.Vega(chart, width=200, height=100) pop_up = folium.Popup(max_width=400).add_child(vega) icon = folium.Icon(color='blue', icon='info-sign') folium.Marker(location=[coord[0], coord[1]], popup=pop_up, icon=icon).add_to(map) return map
def create_map(df, col1): regions_geo = 'regions.geojson' df1 = df.groupby('Region').size() map_1 = folium.Map(location=[52.958, 0.7], zoom_start=7) map_1.choropleth(geo_path=regions_geo, data=df1, columns=['region_code', 'Size'], key_on='properties.region_code', fill_color='BuPu', fill_opacity=0.7, line_opacity=0.2, legend_name='No. of people from region in census') for region in df['Region'].unique().tolist(): df1 = df[df['Region'].str.contains(region)] bar = vincent.Bar(df1[col1].value_counts(), width=350, height=250) xtitle = col1 + "in: " + regions.get(region) bar.axis_titles(x=xtitle, y='') loc = coordinates.get(region) popup1 = folium.Popup(max_width=800, ).add_child( folium.Vega(bar, width=400, height=300)) folium.RegularPolygonMarker(loc, fill_color='#43d9de', radius=12, popup=popup1).add_to(map_1) return map_1
def popups(id): labels=["Total Confirmed cases","Cured/Discharged/Migrated","Death"] sizes=[df_list[0]["Total Confirmed cases (Including 111 foreign Nationals)"][id],df_list[0]["Cured/Discharged/Migrated"][id],df_list[0]["Death"][id]] data={labels[0]:sizes[0],labels[1]:sizes[1],labels[2]:sizes[2]} a=vincent.Pie(data,width=500,height=300) a.legend(state["Name"][i]) popup=folium.Popup(width=550,height=100) folium.Vega(a).add_to(popup) return popup
def add_air_station_marker_with_graph(self, data, *args, **kwargs): """Esta función se encarga de agregar graficos al los marcadores existentes""" locations = data.iloc[:, [1, 2]] station_names = data.iloc[:, [3]] station_ids = list(pd.unique(data.id)) station_groups = data.groupby('id') for station_id in station_ids: filtered_data = station_groups.get_group(station_id) print('***** data get group') print(type(filtered_data)) print(filtered_data.head()) plot_data = filtered_data.groupby( ['magnitude', 'year', 'month', 'day']).agg({ 'value': 'mean' }).reset_index() print('***** data plot data') print(type(plot_data)) print(plot_data.head()) x = [int(hour) for hour in list(plot_data['day'])] y = [int(value) for value in list(plot_data['value'])] print(x) print(y) xy_values = { 'x': x, 'y': y, } scatter_chart = vincent.Scatter(xy_values, iter_idx='x', width=600, height=300) scatter_chart.axis_titles(x='Día', y='Promedio Dióxido de Nitrogeno día') popup_scatter_plot = folium.Popup(max_width=900).add_child( folium.Vega(scatter_chart, height=350, width=700)) air_quality_station = [ filtered_data.iloc[0, 1], filtered_data.iloc[0, 2] ] print(air_quality_station) station_name = [filtered_data.iloc[0, 3]] print(station_name) folium.Marker( location=air_quality_station, tooltip=folium.Tooltip( f'Estación: {station_name[0]}<br>Latitud: {round(air_quality_station[0], 4)}<br>Longitud: {round(air_quality_station[1], 4)}' ), popup=popup_scatter_plot, icon=folium.CustomIcon(icon_image='icons/forecast.png', icon_size=(40, 40))).add_to(self._map)
def createTSMap(pos, timeSeries, zoom_start=4): map = folium.Map(location=pos.items(), zoom_start=4,crs='EPSG4326') df = timeSeries; df.index = df.index.values.astype('M8[D]') chart = vincent.Line(df[['evi','ndvi']],width=300,height=150) chart.legend(title='') chart.axis_titles(x='dates', y='') popup = folium.Popup(max_width=400) folium.Vega(chart.to_json(), height=200, width=450).add_to(popup) folium.Marker(pos.items(), popup=popup,icon=folium.Icon(color='green',icon='info-sign')).add_to(map) wms = folium.features.WmsTileLayer('https://neo.sci.gsfc.nasa.gov/wms/wms', name='MODIS Data', format='image/png', layers='MOD13A2_M_NDVI') wms.add_to(map) return map
def create_map(dataf, year): state_geo = os.path.join('BIN/data/us-states.json') with open('BIN/data/location_state.txt', 'r') as rd: f = rd.read() location = eval(f) with open('BIN/data/states.txt', 'r') as rd: f = rd.read() states = eval(f) prd = pd.read_csv('BIN/data/predictions_in_states.csv', index_col=0) # Initialize the map: m = folium.Map(location=[52, -112], zoom_start=3) df = pd.read_csv('BIN/data/scores.csv', index_col=0) # Add the color for the chloropleth: m.choropleth(geo_data=state_geo, name='choropleth', data=df, columns=['States', 'R^2'], fill_color='GnBu', key_on='feature.id', fill_opacity=0.8, line_opacity=0.6, legend_name='R^2 prediction') folium.LayerControl().add_to(m) m.add_child(folium.LatLngPopup()) for s in states: if s == 'NH' or s == 'WI' or s == 'WV' or s == 'DC': continue folium.RegularPolygonMarker( [location[s][0], location[s][1]], fill_color='#43d9de', radius=4, popup=folium.Popup(max_width=450).add_child( folium.Vega(build_json_plot(dataf, prd, state=s), width=250, height=250))).add_to(m) m.save('BIN/data/map.html') return (m)
def get_polygons_layer(self, clus_polygon_gdf, clus_category_df, layer_name=None, marker_color='#43d9de'): clus_polygon_gdf_json = clus_polygon_gdf.to_json() layer = folium.GeoJson(clus_polygon_gdf_json, name=layer_name) taret_idx = clus_polygon_gdf.index target_df = clus_category_df.loc[taret_idx, :] for idx in taret_idx: folium.RegularPolygonMarker( list(clus_polygon_gdf.loc[idx, 'centroid'])[::-1], fill_color=marker_color, radius=6, popup=folium.Popup(max_width=400).add_child( folium.Vega(self.get_vincent_bar_chart(target_df, idx), width=400, height=270))).add_to(layer) return layer
def add_marker(self, serie, longitude, latitude, arrondissement): liste_annee = [] liste_valeur = [] for annee in serie.index: liste_annee.append(annee) for valeur in serie.values: liste_valeur.append(valeur) scatter_points = { 'x': liste_annee, 'prix au m2': liste_valeur, } scatter_chart = vincent.Bar(scatter_points, iter_idx='x', width=300, height=200) scatter_chart.axis_titles(x='Année', y='Prix au m2') scatter_chart.legend(title=arrondissement) popup = folium.Popup() folium.Vega(scatter_chart, width=400, height=250).add_to(popup) folium.Marker([longitude, latitude], popup=popup).add_to(self.map)
def plotdataPopVega(data,vals): ''' Fuction to create a data popup, as a time servies. What then can be added to a marker ''' df=data[vals] df.fillna(value='null', inplace=True) # Does not handle missing values. line=vincent.Line(df) line.axis_titles(x="Time", y="Mass Concentration") line.legend(title="Values") #find the lenght of the data width=len(df.index) if width <500: width=400 line.width=width line.height=200 vega = folium.Vega(json.loads(line.to_json()), width="30%", height="10%") popup = folium.Popup(max_width=line.width+75).add_child(vega) return popup
def plot_bar_graphs(df_years, html_link, name, color): print('>plotting map...') listOfMedians = prepare_for_data(df_years) barGraphMap = Map(location = latlng, zoom_start = 10, tiles = 'Stamen Terrain') for x,y,df,file,station,ttip in zip(coords['Lat_DD'], coords['Long_DD'], listOfMedians, file_names, coords['Station Number'], coords['Station label']): bar = vincent.GroupedBar(df) bar.axis_titles(x = "Index", y = name) bar.width = 900 bar.height = 250 bar.legend(title='Year') bar.to_json(file) vis1 = os.path.join('/Users/fetch/Desktop/ProjectDirectory', file) folium.Marker(location=[x,y], icon = DivIcon( icon_size=(28,25), icon_anchor=(7, 20), html='<div style="font-family: Rockwell; font-size: 9pt; color :#00664b">'+str(station)+'</div>', ), popup=folium.Popup(max_width=1100).add_child( folium.Vega(json.load(open(vis1)), width= 1000, height=300)) ).add_to(barGraphMap) barGraphMap.add_child(folium.CircleMarker([x,y], fill_color = color, color = color, radius = 22, tooltip = ttip)) barGraphMap.save(html_link+'.html')
import folium import os import json #create a map object m = folium.Map(location=[12.971599, 77.594566], zoom_start=12) # vega data - load from json file vis = os.path.join('datasets', 'vis.json') folium.Marker([12.97, 77.69], popup="<strong>Location 1</strong>", tooltip="Click for more Info").add_to(m) folium.Marker([13.03, 77.55], popup="<strong>Location 2</strong>", tooltip="Click for more Info", icon=folium.Icon(icon='cloud')).add_to(m) folium.Marker( [12.92, 77.67], popup=folium.Popup(max_width=450).add_child( folium.Vega(json.load(open(vis)), width=450, height=250)), ).add_to(m) # generate html file corresponding this map m.save('map.html')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ############################################################################### import json import folium buoy_map = folium.Map(location=[46.3014, -123.7390], zoom_start=7,tiles='Stamen Terrain') popup1 = folium.Popup(max_width=800,).add_child(folium.Vega( json.load(open('/gdata/folium/data/vis1.json')), width=500, height=250)) folium.RegularPolygonMarker([47.3489, -124.708], fill_color='#43d9de', radius=12, popup=popup1).add_to(buoy_map) ############################################################################### popup2 = folium.Popup(max_width=800,).add_child(folium.Vega(json.load(open('/gdata/folium/data/vis2.json')), width=500, height=250)) folium.RegularPolygonMarker([44.639, -124.5339], fill_color='#43d9de', radius=12, popup=popup2).add_to(buoy_map) popup3 = folium.Popup(max_width=800,).add_child(folium.Vega(json.load(open('/gdata/folium/data/vis3.json')), width=500, height=250)) folium.RegularPolygonMarker([46.216, -124.1280], fill_color='#43d9de', radius=12, popup=popup3).add_to(buoy_map) buoy_map.save('/tmp/folium_xx_NOAA_buoys.html') ############################################################################### antarctic_ice_edge = '/gdata/folium/data/antarctic_ice_edge.json' antarctic_ice_shelf_topo = '/gdata/folium/data/antarctic_ice_shelf_topo.json' m = folium.Map( location=[-59.1759, -11.6016], tiles='Mapbox Bright', zoom_start=2 ) folium.GeoJson( antarctic_ice_edge, name='geojson' ).add_to(m) folium.TopoJson( open(antarctic_ice_shelf_topo), 'objects.antarctic_ice_shelf', name='topojson' ).add_to(m)
}, { "domain": { "data": "table", "field": "data.col" }, "name": "color", "range": "category20", "type": "ordinal" }], "width": 400 } #print(data) marker_data.append(json.dumps(data)) #print('done') get_data() m = folium.Map( location=[59.3242, 18.0659], # Stockholm zoom_start=12) for data in marker_data: folium.Marker(location=[get_lat(), get_lon()], popup=folium.Popup(max_width=450).add_child( folium.Vega(data, width=450, height=250))).add_to(m) #m m.save('map.html')
def map_chloro(index_layer, index_plot, min_plot, output_folder): """ Create a Leaflet chloropeth map with Folium and Vega libraries. Each country has his own plot for the given data. :param index_layer: index of the data in the DATA_PATH csv :type index_layer: int :param index_plot: index of the data in the DATA_PATH csv :type index_plot: int :param min_plot: the minimal value of y axes for which the data will be process :type min_plot: float :param output_folder: name of the folder where to save the map :type output_folder: str :return: nothing :rtype: None """ print('Loading capitals data...') # open the json file with the json data of capitals capitals_json = open('utilitaires/data/data_capitals.geojson') capitals = json.load(capitals_json) print("Loading countries data...") # open the json file with dates of quarantine country_json = open('utilitaires/data/data_country.geojson') pays = json.load(country_json) # gestion des titres pour la couche des pays if index_layer == 2: titre_layer = "Nouveaux cas recensés dans la journée d hier" titre_fichier = "nouveaux_cas" elif index_layer == 3: titre_layer = "Nouveaux décès recensés dans la journée d hier" titre_fichier = "nouveaux_deces" elif index_layer == 4: titre_layer = "Nombre de cas total recensés" titre_fichier = "cas_total" elif index_layer == 5: titre_layer = "Nombre de décès total recensés" titre_fichier = "deces_total" elif index_layer == 6: titre_layer = "Nombre de cas recensés la veillepour 10000 habitants" titre_fichier = "nouveaux_cas_10000" elif index_layer == 7: titre_layer = "Nombre de décès recensés la veille pour 10000 habitants" titre_fichier = "nouveaux_deces_10000" elif index_layer == 8: titre_layer = "Nombre total de cas pour 10000 habitants" titre_fichier = "cas_total_10000" elif index_layer == 9: titre_layer = "Nombre total de décès pour 10000 habitants" titre_fichier = "deces_total_10000" # gestion des titres pour les graphiques if index_plot == 2: x_plot = "Jours depuis le premier jour ayant " + str( min_plot) + " nouveaux cas recensés la veille" y_plot = "Nombre de nouveaux cas recensés la veille" elif index_plot == 3: x_plot = "Jours depuis le premier jour ayant " + str( min_plot) + " nouveaux décès recensés la veille" y_plot = "Nombre de nouveaux décès recensés la veille" elif index_plot == 4: x_plot = "Jours depuis un total de " + str(min_plot) + " cas" y_plot = "Nombre de cas recensés " elif index_plot == 5: x_plot = "Jours depuis un total de " + str(min_plot) + " décès" y_plot = "Nombre de décès recensés " elif index_plot == 6: x_plot = "Jours depuis le premier jour ayant " + str( min_plot) + " nouveaux cas recensés la veille pour 10000 habitants" y_plot = "Nombre de nouveaux cas recensés la veille pour 10000 habitants" elif index_plot == 7: x_plot = "Jours depuis le premier jour ayant " + str( min_plot ) + " nouveaux décès recensés la veille pour 10000 habitants" y_plot = "Nombre de nouveaux décès recensés la veille pour 10000 habitants" elif index_plot == 8: x_plot = "Jours depuis un total de " + str( min_plot) + " cas pour 10000 habitants" y_plot = "Nombre de cas recensés pour 10000 habitants" elif index_plot == 9: x_plot = "Jours depuis un total de " + str( min_plot) + " décès pour 10000 habitants" y_plot = "Nombre de décès recensés pour 10000 habitants" print("Processing your given dataset...") # création d'un fichier csv temporaire contenant les données pour la carte selon l'index_layer with open(DATA_PATH, 'r') as f: f_o = csv.reader(f) next(f_o) with open('data.csv', "w") as f_csv: writer = csv.writer(f_csv) writer.writerow(["Country", "Chiffre"]) for line in f_o: # data.csv prend en valeur la date de la veille avec le nombre correspondant, hors World if line[0] == str(YESTERDAY_CUT) and line[1] != 'World': writer.writerow([line[1], line[index_layer]]) # ouverture et lecture du fichier csv créé data = f'data.csv' world_data = pd.read_csv(data) print("Creating the countries's layer of the map...") # initialisation de la carte et des paramètres généraux map = folium.Map(location=[48, 0], zoom_start=3) # création du fonds de carte coloré en fonction des valeurs de la veille folium.Choropleth(geo_data=pays, name='choropleth', data=world_data, columns=['Country', 'Chiffre'], key_on='feature.id', fill_color='OrRd', fill_opacity=0.7, line_opacity=0.2, legend_name=titre_layer).add_to(map) print("Processing plots for each country...") # création d'un point par pays (sur la capitale) pour accueillir les graphiques ensuite for pays in capitals["features"]: # création d'une liste vide qui accueillera un dictionnaire par jour pour le pays donné data_country = [] # création d'un booléen pour savoir si le pays aura un graphique data_plot = False with open(DATA_PATH, 'r') as f_e: f_o = csv.reader(f_e) next(f_o) # la variable i permet non pas d'afficher le jour précis sur l'axe x, mais le numéro du jour en fonction # de la réalisation du paramètre min_plot i = 1 for line in f_o: if pays['properties']['country'] == line[1] and float( line[index_plot]) >= float(min_plot): dico = { "col": "Nombre", "idx": i, "val": float(line[index_plot]) } data_country.append(dico) i += 1 data_plot = True # créer le fichier json nécessaire à Vega pour faire les graphiques if data_plot: with open('country.json', "w") as f: data = { "axes": [{ "scale": "x", "title": x_plot, "type": "x" }, { "scale": "y", "title": y_plot, "type": "y", "grid": True }], "data": [{ "name": "table", "values": data_country }], "height": 400, "legends": [], "marks": [{ "from": { "data": "table", "transform": [{ "keys": ["data.col"], "type": "facet" }] }, "marks": [{ "properties": { "enter": { "stroke": { "field": "data.col", "scale": "color" }, "strokeWidth": { "value": 2 }, "x": { "field": "data.idx", "scale": "x" }, "y": { "field": "data.val", "scale": "y" } } }, "type": "line" }], "type": "group" }], "padding": "auto", "scales": [{ "domain": { "data": "table", "field": "data.idx" }, "name": "x", "range": "width", "nice": True }, { "domain": { "data": "table", "field": "data.val" }, "name": "y", "nice": True, "range": "height" }, { "domain": { "data": "table", "field": "data.col" }, "name": "color", "range": "category20", "type": "ordinal" }], "width": 800 } # écriture du dictionnaire dans un fichier json f.write(json.dumps(data)) # ouverture et lecture de ce nouveau fichier json... with open('country.json', 'r') as f: data_json = json.load(f) custom_icon = folium.features.CustomIcon( icon_image='utilitaires/img/coro.png', icon_size=(14, 14)) # ... pour le donner à folium.Vega dans le marker placé sur la capitale de chaque pays folium.Marker(location=pays['geometry']['coordinates'], popup=folium.Popup(max_width=900).add_child( folium.Vega(data_json, width=900, height=450)), icon=custom_icon).add_to(map) os.remove('country.json') print("Creating the HTML file...") folium.LayerControl().add_to(map) os.mkdir(output_folder) map.save(output_folder + '/map_' + titre_fichier + '.html') country_json.close() capitals_json.close() os.remove('data.csv')
# -*- coding: utf-8 -*- print('=' * 40) print(__file__) from helper.textool import get_tmp_file ################################################################################ import folium import json map_a = folium.Map(location=[46.3014, -123.7390], zoom_start=7, tiles='Stamen Terrain') popup1 = folium.Popup(max_width=800, ).add_child( folium.Vega(json.load(open('/gdata/folium/data/vis1.json')), width=500, height=250)) folium.RegularPolygonMarker([47.3489, -124.708], fill_color='#ff0000', radius=12, popup=popup1).add_to(map_a) ################################################################################ popup2 = folium.Popup(max_width=800, ).add_child( folium.Vega(json.load(open('/gdata/folium/data/vis2.json')), width=500, height=250)) folium.RegularPolygonMarker([44.639, -124.5339], fill_color='#00ff00', radius=12,
'x': segment['Distance / km'], 'y': segment['elevation'], } WIDTH = 400 HEIGHT = 200 line = vincent.Line(data, iter_idx="x", width=WIDTH, height=HEIGHT) line.axis_titles(x='Distance / km', y='Elevation / m') line.x_axis_properties(title_offset=2) line.y_axis_properties(title_offset=-10) line_json = line.to_json() line_dict = json.loads(line_json) popup = folium.Popup(max_width=WIDTH + 50, show=True) chart = folium.Vega(line_dict, width=WIDTH + 50, height=HEIGHT + 50) chart.add_to(popup) marker = folium.Marker( location=segment['latlon'][idx], popup=popup, icon=folium.Icon(icon='star'), ) marker.add_to(the_map) # To store the map as a HTML page: # the_map.save('map_006_chart1.html') # To display the map in a Jupyter notebook: the_map
def create_map(results, cities, statename, time): ## Gets the geoJSON for state and cities calling functions transformCities(cities) transformStates(statename) ## Creates the pup-up graph for the city results using vincent package ## looping over the results dictionary for cityid, df in results.iteritems(): line = vincent.Line(df[['@realDonaldTrump', '@HillaryClinton']]) line.axis_titles(x='date', y='normalized weighted composite score') line.legend(title='Queries') line.width=400 line.height=200 line.axes[0].properties = AxisProperties( labels=PropertySet(angle=ValueRef(value=45), align=ValueRef(value='left'))) line.colors(brew='Set1') line.to_json('data/'+cityid+time+'.json') ## Creates the map outline m = folium.Map([34.569728, -106.119447], tiles="Mapbox Bright", zoom_start=5, min_zoom=5) fg = folium.map.FeatureGroup().add_to(m) ## Adds the states looping over the transformed GeoJSON file ## and sets colour based on time string 'after' for states of ## California and Texas geo_json_states = json.load(open('data/us_states/us_states.json')) for feature in geo_json_states['features']: if time == "after" and feature['properties']['NAME'] == 'California': fg.add_child(MultiPolygon(_locations_mirror(feature['geometry']['coordinates']), color='blue', weight=0)) elif time == "after" and feature['properties']['NAME'] == 'Texas': fg.add_child(MultiPolygon(_locations_mirror(feature['geometry']['coordinates']), color='red', weight=0)) else: fg.add_child(MultiPolygon(_locations_mirror(feature['geometry']['coordinates']), color='grey', weight=0)) ## Add the cities layer looping over the transformed GeoJSON file geo_json_cities = json.load(open('data/us_cities/us_cities.json')) for feature in geo_json_cities['features']: ## Sets colour variable based on most positive nwcs in the analysis ## timeframe places = open('data/' + cities, 'r') for line in places: attr = line.split(";") if attr[0] == feature['properties']['NAME10']: city_id = attr[1] if sum(results[city_id]['@realDonaldTrump']) > sum(results[city_id]['@HillaryClinton']): colour = 'red' else: colour = 'blue' ## Adds the polygon with the set colour fg.add_child(MultiPolygon( _locations_mirror(feature['geometry']['coordinates']), color=colour, weight=0, popup = folium.Popup(max_width=650).add_child(folium.Vega(json.load(open('data/'+city_id+time+'.json')), width=620, height=270)),)) # Saves the map in html format using the string time in filename m.save('sentiment_'+time+'.html')
title_cancel='Exit me', force_separate_button=True).add_to(stamen) FloatImage(url1, bottom=0.08, left=87.4).add_to(stamen) FloatImage(url2, bottom=19, left=82.5).add_to(stamen) FloatImage(url3, bottom=93, left=7.7).add_to(stamen) plugins.Search(yamunanagar, search_zoom=10, geom_type='Polygon').add_to(stamen) folium.Marker(location=[30.50666, 76.52114], icon=icon1, popup=folium.Popup(max_width=500).add_child( folium.Vega(json.load(open(interpolate)), width=500, height=260))).add_to(stamen) folium.CircleMarker(location=[30.445122, 76.672211], radius=13, fill_color='purple', color='purple', popup=folium.Popup(max_width=500).add_child( folium.Vega(json.load(open(stroke)), width=500, height=260))).add_to(stamen) folium.Marker(location=[30.423809, 76.522522], icon=icon2, popup=folium.Popup(max_width=500).add_child( folium.Vega(json.load(open(interpolate)),
radius=75, location=row, popup='This is the sensing radius', color='#3186cc', fill=True, fill_color='#3186cc' ).add_to(Radii) # test markers for vega/altair visualization: folium.Marker( location=[6.942236, 80.615474], icon=folium.Icon(color='blue', icon='bar-chart', prefix='fa'), popup=folium.Popup(max_width=500).add_child( folium.Vega(vis1, width=500, height=250)) ).add_to(dat_grphs) folium.Marker( location=[6.941506, 80.619474], icon=folium.Icon(color='blue', icon='bar-chart', prefix='fa'), popup=folium.Popup(max_width=500).add_child( folium.Vega(vis2, width=500, height=250)) ).add_to(dat_grphs) folium.Marker( location=[6.942936, 80.610974], icon=folium.Icon(color='blue', icon='bar-chart', prefix='fa'), popup=folium.Popup(max_width=500).add_child(
folium.Marker([-1.307466,36.826537], popup='<strong>Location Three</strong>', tooltip=tooltip, icon=folium.Icon(icon='cloud',color='red') ).add_to(myMap) folium.Marker([-1.304481,36.823405], popup='<strong>Location Four</strong>', tooltip=tooltip, icon=customIcon ).add_to(myMap) # 1.303683, 36.824670 folium.Marker([-1.303683,36.824670], popup=folium.Popup(max_width=450).add_child(folium.Vega(json.load(open(vis)),width=450,height=250)) ).add_to(myMap) # Encircle a region folium.CircleMarker( location=[-1.311509,36.814945], radius=50, color='#42bca', fill=True, popup="Qwetu Wilson View", fill_color="#42bca" ).add_to(myMap) #Load GeoJSON
import os import json import requests import folium url = 'https://raw.githubusercontent.com/python-visualization/folium/master/examples/data' vis1 = json.loads(requests.get(f'{url}/vis1.json').text) vis2 = json.loads(requests.get(f'{url}/vis2.json').text) vis3 = json.loads(requests.get(f'{url}/vis3.json').text) # 在图中标记三个位置 m = folium.Map(location=[46.3014, -123.7390], zoom_start=7, tiles='Stamen Terrain') folium.Marker(location=[47.3489, -124.708], popup=folium.Popup(max_width=450).add_child( folium.Vega(vis1, width=450, height=250))).add_to(m) folium.Marker(location=[44.639, -124.5339], popup=folium.Popup(max_width=450).add_child( folium.Vega(vis2, width=450, height=250))).add_to(m) folium.Marker(location=[46.216, -124.1280], popup=folium.Popup(max_width=450).add_child( folium.Vega(vis3, width=450, height=250))).add_to(m) m.save("test1.html")
chania.height = 200 platanias = vincent.StackedBar(df_platanias) platanias.axis_titles(x='Tierarten', y='Anzahl Operationen') platanias.legend(title='platanias') platanias.scales['x'].padding = 0.2 platanias.colors(brew='Pastel1') platanias.width = 350 platanias.height = 200 kreta = folium.Map(location=[35.3220, 25.1001], tiles="Stamen Terrain", zoom_start=8) popup1 = folium.Popup(max_width=800, ).add_child( folium.Vega(heraklion, width=500, height=250)) popup2 = folium.Popup(max_width=800, ).add_child( folium.Vega(agiosNikolaos, width=500, height=250)) popup3 = folium.Popup(max_width=800, ).add_child( folium.Vega(sitia, width=500, height=250)) popup4 = folium.Popup(max_width=800, ).add_child( folium.Vega(kalyves, width=500, height=250)) popup5 = folium.Popup(max_width=800, ).add_child( folium.Vega(rethymno, width=500, height=250)) popup6 = folium.Popup(max_width=800, ).add_child( folium.Vega(chania, width=500, height=250))
import pandas as pd import vincent sbucks = pd.read_csv('starbucks_india.csv') map_mumbai = folium.Map(location=[19.0760, 72.8777]) for index, row in sbucks.iterrows(): lis = [ row['Mon'], row['Tue'], row['Wed'], row['Thu'], row['Fri'], row['Sat'], row['Sun'] ] x = range(len(lis)) bar = vincent.Bar(lis, width=440, height=200) bar.axis_titles(x='Day of Week - ' + row['Name'], y='Foot fall') bar.to_json('vega.json') popup_ = folium.Popup(max_width=800).add_child( folium.Vega(bar, width=500, height=250)) if sum(lis) > 2600: folium.Marker([row['Latitude'], row['Longitude']], popup=popup_, icon=folium.Icon(color='red', icon='star')).add_to(map_mumbai) else: folium.Marker([row['Latitude'], row['Longitude']], popup=popup_, icon=folium.Icon(color='green', icon='star-empty')).add_to(map_mumbai) map_mumbai.save('starbucks_india.html')
coordinates = (20.5937, 78.9629) map1 = folium.Map(location=coordinates, zoom_start=4.5) cases_num = df_list[0]["Total Confirmed cases*"] # In[13]: labels = ["Total Confirmed cases*", "Cured/Discharged/Migrated", "Death"] sizes = [ df_list[0]["Total Confirmed cases*"][36], df_list[0]["Cured/Discharged/Migrated*"][36], df_list[0]["Deaths**"][36] ] data = {labels[0]: sizes[0], labels[1]: sizes[1], labels[2]: sizes[2]} a = vincent.Pie(data, width=500, height=300) a.legend("Covid 19 India") popup = folium.Popup(width=500, height=100) folium.Vega(a).add_to(popup) # In[14]: def popups(id): labels = ["Total Confirmed cases", "Cured/Discharged/Migrated", "Death"] sizes = [ df_list[0]["Total Confirmed cases*"][id], df_list[0]["Cured/Discharged/Migrated*"][id], df_list[0]["Deaths**"][id] ] data = {labels[0]: sizes[0], labels[1]: sizes[1], labels[2]: sizes[2]} a = vincent.Pie(data, width=500, height=300) a.legend(state["Name"][i]) popup = folium.Popup(width=550, height=100)
# macro = MacroElement() # macro._template = Template(template) # m.get_root().add_child(macro) # m #End of adding legend #Adding graph #Graph feature df = pd.read_csv("sample1.csv") print(df.to_string()) # Let's create the vincent chart. scatter_chart = vincent.Bar(df[['Concentration']], width=600, height=300).axis_titles(x='Days', y='Concentrations') # Let's convert it to JSON. scatter_json = scatter_chart.to_json() # Let's convert it to dict. scatter_dict = json.loads(scatter_json) # m = folium.Map([43, -100], zoom_start=4) # Let's create a Vega popup based on df. popup = folium.Popup(max_width=650) folium.Vega(scatter_json, height=350, width=650).add_to(popup) folium.Marker([51.525211, -0.033503], popup=popup).add_to(m) #Graph feature ends m.save('map.html') #Render map print('Map rendering completed')
import folium import pandas as pd import vincent sbucks = pd.read_csv('starbucks_india.csv') map_pune = folium.Map(location = [18.5204, 73.8567]) for index, row in sbucks.iterrows(): lis = [row['Mon'], row['Tue'], row['Wed'], row['Thu'], row['Fri'], row['Sat'], row['Sun']] x = range(len(lis)) bar = vincent.Bar(lis, width=440, height=200) bar.axis_titles(x='Day of week - ' +row['Name'], y='Foot fall') bar.to_json('vega.json') popup_ = folium.Popup(max_width=800).add_child(folium.Vega(bar, width=500, height=250)) if sum(lis) > 2600: folium.Marker([row['Latitude'], row['Longitude']], popup=popup_,icon=folium.Icon(color='red', icon='star')).add_to(map_pune) else: folium.Marker([row['Latitude'], row['Longitude']], popup=popup_,icon=folium.Icon(color='green', icon='star-empty')).add_to(map_pune) map_pune.save('starbucks_india_pune.html')
vis2 = os.path.join('data', 'vis2.json') vis3 = os.path.join('data', 'vis3.json') vis4 = os.path.join('data', 'vis4.json') vis5 = os.path.join('data', 'vis5.json') vis6 = os.path.join('data', 'vis6.json') vis7 = os.path.join('data', 'vis7.json') vis8 = os.path.join('data', 'vis8.json') vis9 = os.path.join('data', 'vis9.json') overlay = os.path.join('data', 'overlay.json') folium.Marker([44.78964787826317, 20.4664977583781], tooltip='Autokomanda', icon=folium.Icon(prefix='fa', icon='bus', markerColor='red'), popup=folium.Popup(max_width=450).add_child( folium.Vega(json.load(open(vis9)), width=450, height=280))).add_to(m), folium.Marker([44.75617744172545, 20.4769512336477], tooltip='Banjica', icon=folium.Icon(prefix='fa', icon='bus', markerColor='blue'), popup=folium.Popup(max_width=450).add_child( folium.Vega(json.load(open(vis8)), width=450, height=280))).add_to(m), folium.Marker([44.768087391424814, 20.49229493597008], tooltip='Brace Jerkovic', icon=folium.Icon(prefix='fa', icon='bus', markerColor='green'), popup=folium.Popup(max_width=450).add_child( folium.Vega(json.load(open(vis7)), width=450, height=280))).add_to(m), folium.Marker([44.8157349019317, 20.491060018369023], tooltip='Bogoslovija', icon=folium.Icon(prefix='fa', icon='bus', markerColor='purple'),