def Dibujar_Grafo_Camino(lati, loni, camlat, camlon): output_file("gmap.html") map_options = GMapOptions(lat=lati[0], lng=loni[0], map_type="roadmap", zoom=5) # For GMaps to function, Google requires you obtain and enable an API key: # # https://developers.google.com/maps/documentation/javascript/get-api-key # # Replace the value below with your personal API key: p = gmap("AIzaSyDf3f-fQDqjQo1Dr5WSO0FDO_nM-HA3qV4", map_options, title="Austin") #IMPORTANTE: Profesor, si cuenta con algun error al momento de visualizar el grafico, por favor #coloque su API key personal como primer parametro de la función que se esta llamando en la linea #de codigo anterior. source = ColumnDataSource(data=dict(lat=lati, lon=loni)) source2 = ColumnDataSource(data=dict(lat=camlat, lon=camlon)) p.circle(x="lon", y="lat", size=7, fill_color="blue", fill_alpha=0.8, source=source) p.circle(x="lon", y="lat", size=10, fill_color="red", fill_alpha=0.8, source=source2) p.line(camlon, camlat, line_color="red") show(p)
def create_map(): z = zoom.value lt = lat.value lg = lon.value day = mapping_day(days_options.active) hour = mapping_hour(slider.value) df['checkin_at_hour'] = checkin_at_hour( day, hour) # adds column df['checkin_at_hour'] for use in size calculation sz = sizes(df['checkin_at_hour'], z) df['flag_1'] = selection_1(neighborhood.value) df['flag_2'] = selection_2(ambience.value) df['flag_3'] = selection_3(alcohol.value) df['flag_4'] = selection_4(category.value) df['flag_5'] = agg_selection(df['flag_1'], df['flag_2'], df['flag_3'], df['flag_4']) clr = colors(df['flag_5']) alp = alpha(df['flag_5']) map_options = GMapOptions(lat=lt, lng=lg, map_type="roadmap", zoom=z) bus_hover = HoverTool(tooltips=[('Business Name', '@name'), ('Reviews', '@review_count'), ('Checkins', '@checkin_at_hr')], names=["bus_hover"]) p = gmap("AIzaSyAQBImT1FpLK1aQvKq1e-Cfs1xd_NzC0mY", map_options, title="Vegas businesses", plot_width=550, plot_height=550, tools=[bus_hover, 'reset', 'pan', 'lasso_select'], toolbar_location="above") source = ColumnDataSource(data=dict(lat=df['latitude'], lon=df['longitude'], size=sz, color=clr, alpha=alp, name=df['name'], review_count=df['review_count'], checkin_at_hr=df['checkin_at_hour'])) p.circle(x="lon", y="lat", size="size", fill_alpha="alpha", fill_color="color", name="bus_hover", line_width=1, line_alpha=0, hover_alpha=1.0, source=source) p.outline_line_alpha = 0 p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None p.xaxis.visible = False p.yaxis.visible = False return p
def showmap(): tools = "pan,wheel_zoom,box_zoom,reset,save,hover,zoom_in,box_edit,poly_draw" # tools = " box_edit, box_select, box_zoom, click, crosshair, help, hover, lasso_select, pan, point_draw, poly_draw, poly_edit, poly_select, previewsave, redo, reset, save, tap, undo, wheel_zoom, xbox_select, xbox_zoom, xpan, xwheel_pan, xwheel_zoom, xzoom_in, xzoom_out, ybox_select, ybox_zoom, ypan, ywheel_pan, ywheel_zoom, yzoom_in, yzoom_out, zoom_in" map_options = GMapOptions(lat=0.3476, lng=32.5825, map_type="roadmap", zoom=13) GOOGLE_API_KEY = "AIzaSyAFCR-n7VxtftzPKR4gCje1T-cAxQXn7S8" plot = gmap(GOOGLE_API_KEY, map_options, tools=tools, title="Crimes visualizing center", height=700, width=1100) latitude_list, longitude_list, colors_list = get_co_ordinates() source = ColumnDataSource( data=dict(lat=latitude_list, lon=longitude_list, color=colors_list)) plot.circle(x="lon", y="lat", size=15, fill_color="color", fill_alpha=0.8, source=source) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) storage_path = os.path.join(BASE_DIR, 'pathfinder/templates/pages') map_path = os.path.join(storage_path, 'gmap_plot.html') output_file(map_path) print("saved...") save(plot)
def create_all(self): """ Creates a map with all incident reports plotted onto a google maps of Seattle. The map is interactive, and the output file is an HTML document "gmap.html" """ output_file("gmap.html") map_options = GMapOptions(lat=47.608013, lng=-122.335167, map_type="roadmap", zoom=12) p = gmap("AIzaSyCaSPqCN6IgZb_vqQZ0F10LmiyK_QXd5sM", map_options, title="Seattle", plot_width=1000, plot_height=1000) for streets in self._df["address"].unique(): is_street = self._df["address"] == streets latitude = self._df[is_street].loc[:, "latitude"] longitude = self._df[is_street].loc[:, "longitude"] source = ColumnDataSource( data=dict(lat=[latitude], lon=[longitude])) p.circle(x="lon", y="lat", size=10, fill_color="blue", fill_alpha=0.8, source=source) show(p)
def geo_tab(df): df_sample = df.sample( frac=.25) # Show 25% of the records, otherwise the map will be slow. map_options = GMapOptions(lat=47.335728, lng=4.115118, map_type="roadmap", zoom=5) api_key = "AIzaSyAhJoQsJr9IdsbXthpM4i84HsYvJtXxLXc" # Output backend WebGL for better performance. p = gmap(api_key, map_options, title="Review Locations", output_backend="webgl") data = dict(lat=df_sample['lat'], lon=df_sample['lng']) p.circle(x="lon", y="lat", size=12, fill_color="blue", fill_alpha=0.8, source=data) tab = Panel(child=p, title='Review Locations') return tab
def initiate_guest_view(api_key, map_start=c.ADDRESS): """ Generates and updates visualization layout for guest users :params api_key string: :params map_start string: """ # Centers map and plots listing locations city_lat, city_long = get_city_location(map_start, api_key) map_options = GMapOptions(lat=city_lat, lng=city_long, map_type='roadmap', zoom=11) plt = gmap(api_key, map_options, title=map_start) plt.circle(x=c.LONGITUDE, y=c.LATITIUDE, size=4, fill_color=c.PRICE_COLOR, fill_alpha=0.8, source=SOURCE, legend=c.PRICE_VALUE) # Configures hover display tooltips = [('Price', '$' + '@price'), ('Valued at', '$' + '@predicted_price'.split('.')[0]), ('Value', '@price_value'), ('Sentiment Score', '@sentiment')] plt.add_tools(HoverTool(tooltips=tooltips)) guest_layout = layout([[WIDGETS_GUEST, plt]], sizing_mode=c.STRETCH_BOTH) curdoc().clear() curdoc().add_root(guest_layout)
def map(request): map_options = GMapOptions(lat=30.2861, lng=-97.7394, map_type="roadmap", zoom=11) # init scatter plot api_key = settings.GOOGLE_API_KEY bokehAx = bp.gmap(api_key, map_options, title="Austin") source = ColumnDataSource(data={ 'lat': [30.29, 30.20, 30.29], 'lon': [-97.70, -97.74, -97.78] }) bokehAx.circle(x="lon", y="lat", size=15, fill_color="blue", fill_alpha=0.8, source=source) # labels etc #bokehAx.title.text = '' #bokehAx.xaxis.axis_label = 'lat' #bokehAx.yaxis.axis_label = 'lon' plotResponse = file_html(bokehAx, CDN, 'map') return HttpResponse(plotResponse)
def mapOut(gmap_api, long, la): output_file("gmap.html") map_options = GMapOptions(lat=42.35, lng=-71.1, map_type="roadmap", zoom=11) # For GMaps to function, Google requires you obtain and enable an API key: # # https://developers.google.com/maps/documentation/javascript/get-api-key # # Replace the value below with your personal API key: p = gmap(gmap_api, map_options, title="All restarants serves pizza in Boston") source = ColumnDataSource(data=dict(lat=la, lon=long)) p.circle(x="lon", y="lat", size=15, fill_color="blue", fill_alpha=0.8, source=source) show(p)
def make_plot(src): path = '../data/' with open(path + 'client_secret.json') as f: data = json.load(f) api_key = data['google_api_key'] map_options = GMapOptions(lat=40.76, lng=-73.95, map_type='roadmap', zoom=12, styles=map_style) call_map = gmap(api_key, map_options, title='311 Calls by Location', plot_width=850, plot_height=850) call_map.circle(x='lon_round', y='lat_round', size='sizes', source=src, fill_alpha=0.8, fill_color='tomato', line_color='firebrick') hover = HoverTool(tooltips=[( 'Longitude', '@lon_round{0.0}'), ('Latitude', '@lat_round{0.0}'), ('Calls', '@count{0,0}')]) call_map.add_tools(hover) call_map = style(call_map) return call_map
def plot(lat, lng, zoom=17, map_type='roadmap'): from bokeh.io import show from bokeh.plotting import gmap from bokeh.models import GMapOptions bokeh_width, bokeh_height = 1000, 600 api_key = "AIzaSyB4y5u1q0_-4kVQpSMGkH_dxpnzn8PL-dQ" gmap_options = GMapOptions(lat=lat, lng=lng, map_type=map_type, zoom=zoom) p = gmap(api_key, gmap_options, title='Pays de Gex', width=bokeh_width, height=bokeh_height) # beware, longitude is on the x axis ;-) center = p.circle([lng], [lat], size=10, alpha=0.5, color='yellow') car_coords, car_coords_x, car_coords_y, red_x, red_y = vehicle_dots() # print(car_coords) # see how we set radius instead of size: center = p.circle(car_coords_x, car_coords_y, size=10, alpha=0.5, color='blue') center = p.circle(red_x, red_y, size=10, alpha=0.5, color='red') return p
def main(): map_options = GMapOptions(lat=49.2081, lng=10.7394, map_type='roadmap', zoom=11) fig = gmap( GOOGLE_API_KEY, map_options, title='', ) # tile_provider = get_provider('CARTODBPOSITRON') # fig = figure( # x_axis_type='mercator', y_axis_type='mercator', # ) # fig.add_tile(tile_provider) fig.width = PLOT_WIDTH fig.height = 700 source = setup_source() circle = Circle(x='lon', y='lat', size=15, fill_color='blue', fill_alpha=0.8) fig.add_glyph(source, circle) return components(fig)
def make_plot(field_name): # Set the format of the colorbar min_range = format_df.loc[format_df['field'] == field_name, 'min_range'].iloc[0] max_range = format_df.loc[format_df['field'] == field_name, 'max_range'].iloc[0] field_format = format_df.loc[format_df['field'] == field_name, 'format'].iloc[0] # Instantiate LinearColorMapper that linearly maps numbers in a range, into a sequence of colors. color_mapper = LinearColorMapper(palette=palette, low=min_range, high=max_range) # Create color bar. format_tick = NumeralTickFormatter(format=field_format) color_bar = ColorBar(color_mapper=color_mapper, label_standoff=6, formatter=format_tick, border_line_color=None, location=(0, 0)) # Create figure object. map_options = GMapOptions(lat=43.60, lng=1.44, map_type="roadmap", zoom=12) verbage = format_df.loc[format_df['field'] == field_name, 'verbage'].iloc[0] p = gmap(GOOGLE_API_KEY, map_options, title=verbage + ' by Neighborhood for Apartments for Rent in Toulouse (2020)', plot_height=650, plot_width=850, toolbar_location="below") p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None p.axis.visible = False # Add patch renderer to figure. p.patches('xs', 'ys', source=geosource, fill_color={ 'field': field_name, 'transform': color_mapper }, line_color='black', line_width=0.25, fill_alpha=0.5) # Specify color bar layout. p.add_layout(color_bar, 'right') # Add the hover tool to the graph p.add_tools(hover) return p
def make_plot(store_now, store_future, ecom_zipcode_all): # Source: http://www.bigendiandata.com/2017-06-27-Mapping_in_Jupyter/ from bokeh.io import output_file, output_notebook, show from bokeh.models import GMapOptions, ColumnDataSource, CategoricalColorMapper, HoverTool, LassoSelectTool from bokeh.palettes import RdBu3 from bokeh.plotting import gmap map_options = GMapOptions(lat=42.37, lng=-71.23, map_type="roadmap", zoom=10) plot = gmap(map_options=map_options, google_api_key='AIzaSyCrnuAv4K0j80AZzUsYFS2NwyY49-yMXRI', plot_width=780, plot_height=780, output_backend="webgl") plot.title.text = "PUMA Retail Store and Ecommerce Transactions" mapper = CategoricalColorMapper( factors=['Unreached', 'Reached', 'Future Reach'], palette=[RdBu3[1], RdBu3[0], RdBu3[2]]) plot1 = plot.square(x="lng", y="lat", size=20, color='blue', source=store_now) plot2 = plot.square(x="lng", y="lat", size=20, color='red', source=store_future) plot3 = plot.circle(x="lng", y="lat", size='Size', fill_color={ 'field': 'inrange', 'transform': mapper }, source=ecom_zipcode_all, legend='inrange') tooltips1 = [("Ship To ZipCode", "@store_zip"), ("Ship To City", "@in_city"), ('Ecom Transactions', '@Transactions')] plot.add_tools(HoverTool(tooltips=tooltips1, renderers=[plot3])) tooltips3 = [("Store ZipCode", "@store_zip"), ("City located", "@in_city"), ('Ecom Transactions in range', '@Transactions')] plot.add_tools(HoverTool(tooltips=tooltips3, renderers=[plot2])) plot.add_tools(LassoSelectTool()) return plot
def option(): if request.method == 'GET': route_n = request.args.get('route_n', '') option = get_option(route_n) if option == "Route1": df = pd.read_csv("./data/df1out.csv") coords, lat_mean, lon_mean = get_coords(df) elif option == "Route2": df = pd.read_csv("./data/df2out.csv") coords, lat_mean, lon_mean = get_coords(df) elif option == "Route3": df = pd.read_csv("./data/df3out.csv") coords, lat_mean, lon_mean = get_coords(df) elif option == "Route4": df = pd.read_csv("./data/df4out.csv") coords, lat_mean, lon_mean = get_coords(df) elif option == "Route5": df = pd.read_csv("./data/df5out.csv") coords, lat_mean, lon_mean = get_coords(df) figure = make_plot(df) fig_script, fig_div = components(figure) map_options = GMapOptions(lat=lat_mean, lng=lon_mean, map_type="roadmap", zoom=14) #map_options = GMapOptions(lat=51.759, lng=-1.255, map_type="roadmap", zoom=15) google_api = 'AIzaSyBdPAkzHMWahHjT9ml9zGeM6pR3u-VucKc' fig_map = gmap(google_api, map_options, title="Route Taken", plot_height=400, plot_width=500) fig_map.xaxis.axis_label = 'Longitude' fig_map.yaxis.axis_label = 'Latitude' source = ColumnDataSource(coords) fig_map.circle(x="lon", y="lat", size=5, fill_color="blue", fill_alpha=0.8, source=source) # show(fig_map) script2, div2 = components(fig_map) #figure = make_plot() #fig_script, fig_div = components(figure) return render_template("location2.html.j2", option=option, route_n=route_n, fig_script=fig_script, fig_div=fig_div, bkversion=bokeh.__version__, df=df, script2=script2, div2=div2)
def create_map(): z = zoom.value lt = lat.value lg = lon.value day = mapping_day(days_options.active) hour = mapping_hour(slider.value) df['checkin_at_hour'] = checkin_at_hour( day, hour) # adds column df['checkin_at_hour'] for use in size calculation # checkin_vals = df['checkin_at_hour'] sz = sizes(df['checkin_at_hour'], z) print(sz[:20]) df['flag_1'] = selection_1(neighborhood.value) df['flag_2'] = selection_2(ambience.value) df['flag_3'] = selection_3(alcohol.value) df['flag_4'] = selection_4(category.value) df['flag_5'] = agg_selection(df['flag_1'], df['flag_2'], df['flag_3'], df['flag_4']) clr = colors(df['flag_5']) alp = alpha(df['flag_5']) output_file("gmap.html") map_options = GMapOptions(lat=lt, lng=lg, map_type="roadmap", zoom=z) bus_hover = HoverTool(tooltips=[('Business Name', '@name'), ('Reviews', '@review_count'), ('Checkins', '@checkin_at_hr')], names=["bus_hover"]) p = gmap("AIzaSyBZ66UcTIUAyZBWhrhs8JLTzth9yMorgQU", map_options, title="Vegas", plot_width=800, tools=[bus_hover, 'reset', 'pan', 'lasso_select']) source = ColumnDataSource(data=dict(lat=df['latitude'], lon=df['longitude'], size=sz, color=clr, alpha=alp, name=df['name'], review_count=df['review_count'], checkin_at_hr=df['checkin_at_hour'])) p.circle(x="lon", y="lat", size="size", fill_alpha="alpha", fill_color="color", name="bus_hover", line_width=1, line_alpha=0, hover_alpha=1.0, source=source) return p
def plot(df, palette, filename): df['latitude'] = np.float64(df['latitude']) df['longitude'] = np.float64(df['longitude']) latitude_list = [x for x in df['latitude'].values] longitude_list = [x for x in df['longitude'].values] rent = ['$' + str(x) for x in df['Rent'].values] scale = np.array(df['Rent'].values) / max(df['Rent'].values) new_scale = [int(i * 10) for i in scale] scale_drop_duplicates = list(set(new_scale)) radius = [x * 100 for x in new_scale] colors = brewer[palette][9] colors = colors[::-1] colormap = dict(zip(scale_drop_duplicates, colors)) colors = [colormap[x] for x in new_scale] map_options = GMapOptions(lat=33.4484, lng=-112.0740, map_type="roadmap", zoom=12) api_key = config.gmap_api_key source = ColumnDataSource(data=dict(lat=latitude_list, lon=longitude_list, radius=radius, colors=colors, alpha=scale, label=rent)) hover = HoverTool(tooltips=[("Rent", "@label")]) bokeh_plot = gmap(api_key, map_options, tools=[hover, WheelZoomTool(), PanTool(), BoxZoomTool()], title='Phoenix Housing Data (Rent per Sq. Ft.)') bokeh_plot.circle(x="lon", y="lat", radius="radius", fill_color="colors", line_color="colors", line_width=2, line_alpha=0.3, fill_alpha=0.8, source=source) output_file(filename) png_file = 'Figures/' + filename.split('.')[0] + '.png' export_png(bokeh_plot, filename=png_file) show(bokeh_plot)
def make_plot(self): hover_tool = HoverTool(tooltips=[ ("Station", "@target_station"), ]) dataframe = self.found_wsc_stations_source.data current_loc = self.current_location_source.data map_options = GMapOptions( lat=current_loc['lat'][0], lng=current_loc['lng'][0], map_type="hybrid", zoom=8 ) BASE_DIR = os.path.dirname(os.path.dirname( os.path.dirname( os.path.dirname(os.path.abspath(__file__))))) with open('dashboard/api_key/client_secret_548109306400.json') as f: GOOGLE_API_KEY = json.load(f) self.plot = gmap(google_api_key=GOOGLE_API_KEY['api_key'], name='map', map_options=map_options, width=900, height=400, tools=TOOLS, title=TITLE) self.plot.circle(x="Longitude", y="Latitude", size=15, fill_color="blue", fill_alpha=0.8, source=self.found_wsc_stations_source, # set visual properties for selected glyphs selection_color="orange", nonselection_fill_alpha=0.6, legend="WSC Stations" ) self.plot.inverted_triangle(x="lng", y="lat", size=11, fill_color="red", fill_alpha=0.8, source=self.current_location_source, legend='Target Location') self.plot.on_event(DoubleTap, self.map_callback) return column(row(self.plot, column(self.search_parameter_text, self.lat_input, self.lng_input, self.coordinate_input_warning, self.search_distance_select, ) ), self.station_summary_text, self.station_summary_table, )
def makeplot(): conn = sqlite3.connect("yelp.db") cur = conn.cursor() df = pd.read_sql_query( ''' Select latitude, longitude, name, Sentiment From Temp ''', conn) df['Sentiment'] = np.float64(df['Sentiment']) df1 = df.groupby(['name', 'latitude', 'longitude']).agg({'Sentiment': 'mean'}) df1['Sentiment'] = np.where(df1['Sentiment'] > 0, 1, 0) df1.reset_index(inplace=True) names = [x for x in df1['name'].values] latitude_list = [float(x) for x in df1['latitude'].values] longitude_list = [float(x) for x in df1['longitude'].values] sentiment = [x for x in df1['Sentiment'].values] colors = ['green' if x == 1 else 'red' for x in sentiment] legends = ['Positive' if x == 1 else 'Negative' for x in sentiment] map_options = GMapOptions(lat=33.4484, lng=-112.0740, map_type="roadmap", zoom=12) api_key = config.gmap_api_key source = ColumnDataSource(data=dict(lat=latitude_list, lon=longitude_list, label=names, color=colors, legend=legends)) hover = HoverTool(tooltips=[("Name", "@label")]) bokeh_plot = gmap(api_key, map_options, tools=[hover, WheelZoomTool(), PanTool(), BoxZoomTool()], title='Business Locations') bokeh_plot.circle(x="lon", y="lat", size=4, color='color', legend_field='legend', fill_alpha=0.8, source=source) output_file('sentimentmap.html') export_png(bokeh_plot, filename="Figures/sentimentmap.png") show(bokeh_plot) conn.commit()
def make_map(area, lat, lng, size): map_options = GMapOptions(lat=lat, lng=lng, map_type="satellite", zoom=size) data2 = data1[(data1.Region == area) & (data1.Date == data1[ (data1.Region == area)].Date.unique()[0])] source = ColumnDataSource(data2) p_map = gmap("AIzaSyDzhOqlGE7EN2Vy9gy5JRbupJlCrcR09iU", map_options, title=area + " Map" + ' (' + str(lat) + ', ' + str(lng) + ')', plot_width=300, plot_height=400, toolbar_location=None) p_map.axis.visible = False color = data2.color[::-1] data3 = { 'Apple': [[[15.711965, 15.713562, 15.713219, 15.712334, 15.712369, 15.711703], [15.713568, 15.713822, 15.713044, 15.712171], [15.713609, 15.714764, 15.714596, 15.713955, 15.713237], [15.713650, 15.713846, 15.715750, 15.715557]], [[47.223237, 47.223645, 47.225226, 47.224970, 47.224338, 47.223936], [47.223570, 47.222634, 47.222503, 47.223248], [47.223685, 47.223952, 47.224847, 47.225322, 47.225234], [47.223588, 47.222628, 47.222990, 47.223961]]], 'Hofer': [[[15.641922, 15.641447, 15.643072, 15.644024, 15.645142, 15.645208], [15.645323, 15.646113, 15.649310, 15.647611, 15.647018], [15.650919, 15.647627, 15.647918, 15.650740, 15.651293, 15.652723]], [[47.158920, 47.158138, 47.157579, 47.157747, 47.157568, 47.157859], [47.157523, 47.159077, 47.156907, 47.156023, 47.157243], [47.158064, 47.155710, 47.154601, 47.156329, 47.155954, 47.156926]]], 'Perl': [[[15.679830, 15.677504, 15.678461, 15.680532], [15.680532, 15.681283, 15.684410, 15.683781]], [[47.131326, 47.129918, 47.129489, 47.130734], [47.131063, 47.130454, 47.132222, 47.132854]]] } for x, y, z in zip(data3[area][0], data3[area][1], color): p_map.patch(x, y, fill_color=z, fill_alpha=0.1, line_color=z) labels = LabelSet(x="lon", y="lat", text="Area", x_offset=3, y_offset=5, text_font_size="9pt", text_color="white", source=source, text_align='center') p_map.add_layout(labels) return p_map
def getLocations(): all_tweets = pd.read_csv("all_tweets.csv") print(len(all_tweets)) #Get Geo Coordinates all_tweets = get_coordinates(all_tweets) output_file("templates/gmap.html") pos_data = all_tweets.dropna()[all_tweets['model_sentiment'] == 'positive'] neg_data = all_tweets.dropna()[all_tweets['model_sentiment'] == 'negative'] ntl_data = all_tweets.dropna()[all_tweets['model_sentiment'] == 'neutral'] map_options = GMapOptions(lat=30.2861, lng=-97.7394, map_type="roadmap", zoom=3) # For GMaps to function, Google requires you obtain and enable an API key: # # https://developers.google.com/maps/documentation/javascript/get-api-key # # Replace the value below with your personal API key: p = gmap("AIzaSyBNoWs1e8I7XvEBcA4KbsR8hKP4mJzot2U", map_options) source = ColumnDataSource(data=pos_data) p.circle(x="longitude", y="latitude", size=15, fill_color="green", fill_alpha=0.8, source=source) source = ColumnDataSource(data=neg_data) p.circle(x="longitude", y="latitude", size=15, fill_color="red", fill_alpha=0.8, source=source) source = ColumnDataSource(data=ntl_data) p.circle(x="longitude", y="latitude", size=15, fill_color="blue", fill_alpha=0.8, source=source) show(p) return render_template("locations.html")
def __init__(self, stations, origin=(52.2070, 0.1131)): self.stations = stations self.locations = [i.coord for i in self.stations] self.options = GMapOptions(lat=origin[0], lng=origin[1], map_type="roadmap", zoom=11) self.tools = "crosshair,pan,wheel_zoom,box_select,lasso_select,reset,save" self.plot = gmap(environ.get('API_KEY'), self.options, title="Station locations", tools=self.tools, active_scroll="wheel_zoom")
def gmap_activities(start, finish, activity_group, google_key): f''' # Google Maps Activities: {start.split()[0]} - {finish.split()[0]} / {activity_group} ''' ''' $contents ''' ''' ## Read Data ''' s = session('-v2') data_frames = [ activity_statistics(s, LATITUDE, LONGITUDE, activity_journal=aj) for aj in s.query(ActivityJournal).filter( ActivityJournal.start >= local_date_to_time(start), ActivityJournal .start < local_date_to_time(finish), ActivityJournal.activity_group == ActivityGroup.from_name(s, activity_group)).all() ] data_frames = [ data_frame.dropna() for data_frame in data_frames if not data_frame.dropna().empty ] print(f'Found {len(data_frames)} activities') ''' ## Calculate Centre ''' ll = [(data_frame[LATITUDE].mean(), data_frame[LONGITUDE].mean()) for data_frame in data_frames] ll = list(zip(*ll)) ll = (median(ll[0]), median(ll[1])) ''' ## Display ''' map_options = GMapOptions(lat=ll[0], lng=ll[1], map_type="roadmap", scale_control=True) f = gmap( google_key, map_options, title=f'{start.split()[0]} - {finish.split()[0]} / {activity_group}', tools='pan,zoom_in,zoom_out,reset,undo,redo,save', output_backend=DEFAULT_BACKEND) for data_frame in data_frames: f.line(x=LONGITUDE, y=LATITUDE, source=data_frame) show(f)
def plot(lat, lng, zoom=10, map_type='roadmap'): from bokeh.io import show from bokeh.plotting import gmap from bokeh.models import GMapOptions gmap_options = GMapOptions(lat=lat, lng=lng, map_type=map_type, zoom=zoom) p = gmap(api_key, gmap_options, title='Pays de Gex', width=bokeh_width, height=bokeh_height) # beware, longitude is on the x axis ;-) center = p.circle([lng], [lat], size=10, alpha=0.5, color='red') return p
def plot_map(dataframe, column, min_value=None, max_value=None, save_png=False): """ Visualization of the location (using Google Maps). :param dataframe: (pd.DataFrame) a data frame that stores location data for visualization (must have "longitude" and "latitude" columns) :param column: (str) the column whose values will be colored :param min_value: (float) min value for color bar :param max_value: (float) max value for color bar :param save_png: (bool) save or not the picture to png-format :return: None """ map_options = GMapOptions(lat=dataframe[dataframe['latitude'] > 0].mean().latitude, lng=dataframe[dataframe['longitude'] > 0].mean().longitude, map_type="roadmap", zoom=10) p = gmap('GoogleMaps-API', map_options, title=f"Spatio-temporal clusters") source = ColumnDataSource( data=dict(lat=dataframe.latitude.to_list(), lon=dataframe.longitude.to_list(), color=dataframe[column].tolist()) ) if min_value is None: min_value = min(dataframe[column].tolist()) if max_value is None: max_value = max(dataframe[column].tolist()) color_mapper = LinearColorMapper(palette=Viridis256, low=min_value, high=max_value) p.circle( x="lon", y="lat", size=10, fill_color={'field': 'color', 'transform': color_mapper}, line_color={'field': 'color', 'transform': color_mapper}, fill_alpha=0.3, line_alpha=0.3, source=source ) # add color bar color_bar = ColorBar(color_mapper=color_mapper, label_standoff=12, border_line_color=None, location=(0, 0)) p.add_layout(color_bar, 'right') if save_png: export_png(p, filename=f"../output/time_cluster.png") # output_file(f'{column}_map.html') # save(p) else: show(p)
def _geo_plot(self, lat, long, col, ini_lat, ini_long, title): map_options = GMapOptions(lat=ini_lat, lng=ini_long, map_type="hybrid", zoom=11) p = gmap(self.key, map_options, title=title) source = ColumnDataSource(data=dict(lat=lat, lon=long)) p.circle(x="lon", y="lat", size=15, fill_color=col, fill_alpha=0.8, source=source) show(p)
def plot_patches_on_gmap(vertex_xcoords, vertex_ycoords, api_key, solid_fill=None, values=None, color_mapper=None, map_options=None, title=None, alpha=0.25): if values is not None: assert color_mapper is not None, "must provide a color_mapper if providing a list of colors" else: assert solid_fill is not None, "must provide a solid fill color if not providing a list of colors" plot = bk.gmap(api_key, map_options=map_options, title=title) plot.add_tools(PanTool(), WheelZoomTool(), ResetTool()) data = dict(xs=vertex_xcoords, ys=vertex_ycoords) if values is not None: data['colors'] = values source_patches = bk.ColumnDataSource(data=data) if values is not None: patches_glyph = plot.patches('xs', 'ys', fill_alpha=alpha, fill_color={ "field": "colors", "transform": color_mapper }, source=source_patches, line_width=0) color_bar = ColorBar(color_mapper=color_mapper, border_line_color=None, location=(0, 0), scale_alpha=alpha, title="minutes") plot.add_layout(color_bar, 'right') else: patches_glyph = plot.patches('xs', 'ys', fill_alpha=alpha, fill_color=solid_fill, source=source_patches, line_width=0) return plot
def _create_choropleth_map(source, width=600, height=1000): """ Create a choropleth map with of incidents in Amsterdam-Amstelland. params ------ source: a Bokeh GeoJSONDataSource object containing the data return ------ a Bokeh figure showing the spatial distribution of incidents in over the region """ map_colors = ['#f2f2f2', '#fee5d9', '#fcbba1', '#fc9272', '#fb6a4a', '#de2d26'] color_mapper = LogColorMapper(palette=map_colors) nonselection_color_mapper = LogColorMapper(palette=gray(6)[::-1]) tooltip_info = [("index", "$index"), ("(x,y)", "($x, $y)"), ("#incidents", "@incident_rate"), ("location id", "@location_id")] map_tools = "pan,wheel_zoom,tap,hover,reset" # get google maps API key with open("./Data/googlemapskey.txt") as f: maps_api_key = f.readline() map_options = GMapOptions(lat=52.35, lng=4.9, map_type="roadmap", zoom=11) p = gmap(maps_api_key, map_options,tools=map_tools, plot_width=width, plot_height=height, x_axis_location=None, y_axis_location=None) p.xaxis.visible=False p.yaxis.visible=False # p = figure(title="Spatial distribution of incidents in Amsterdam-Amstelland", # tools=map_tools, x_axis_location=None, y_axis_location=None, # height=height, width=width, tooltips=tooltip_info) # p.x_range = Range1d(4.66, 5.10) # p.y_range = Range1d(52.18, 52.455) # p.grid.grid_line_color = None # p.add_tile(CARTODBPOSITRON) patches = p.patches('xs', 'ys', source=source, fill_color={'field': 'incident_rate', 'transform': color_mapper}, fill_alpha=0.5, line_color="black", line_width=0.3, nonselection_fill_color={'field': 'incident_rate', 'transform': nonselection_color_mapper}) return p, patches
def __init__(self, InverterSettings, StorageSettings): self.InvSettings = InverterSettings self.StorageSettings = StorageSettings self.clearTopologyData() self.source = ColumnDataSource(self.TopologyData) self.sourceNode = ColumnDataSource(self.NodeData) callback = CustomJS(code="""console.info("hello TapTool")""") tt = TapTool(callback=callback) map_options = GMapOptions(lat=36, lng=-106, map_type='roadmap', zoom=8) self.TopologyPlot = gmap('AIzaSyCiQT0TLjv0G25HN03eRJjQVfk6xRsMITo', map_options, plot_width=1200, plot_height=1000) self.TopologyPlot.toolbar.logo = None self.TPmulti_lines = self.TopologyPlot.multi_line(xs='Xs', ys='Ys', source=self.source, line_width=1, line_alpha=1.0,line_color="darkblue", legend='Edges') self.TPcircles = self.TopologyPlot.circle(x='X', y='Y', source=self.sourceNode, legend='Nodes', color='PV', radius=20, hover_color="red") self.TopologyPlot.toolbar.active_tap = 'auto' self.TopologyPlot.xaxis.axis_label = 'Longitude' self.TopologyPlot.yaxis.axis_label = 'Latitude' self.TopologyPlot.legend.location = "top_right" self.TopologyPlot.legend.click_policy = "hide" hoverBus = HoverTool(show_arrow=False, line_policy='next', tooltips=[ ("Element", "@Name"), ("Class", "@Class"), ("Phases", "@Phases"), ("Distance", "@D") ]) self.TopologyPlot.tools.append(hoverBus) self.TopologyPlot.tools.append(TapTool()) self.TopologyPlot.tools.append(ZoomInTool()) self.TopologyPlot.tools.append(ZoomOutTool()) self.final_layout = self.TopologyPlot self.TPcircles.data_source.on_change('selected', self.test) #taptool = self.TopologyPlot.select(type=TapTool) #taptool.callback = callback return
def coordinates(coordinates_csv, solution): # read csv file with pandas to abstract tabel reader = pd.read_csv('data/StationsNationaal.csv') source = ColumnDataSource(data=reader) # coordinates of Utrecht, because that's sort of the middle of the Netherlands map_options = GMapOptions(lat=52.0907374, lng=5.1214201, map_type="terrain", zoom=7, styles=style.style_options) # gmap function with API key p = gmap("YOURAPIKEYHERE", map_options, title="Visualisatie") # add circles for all stations p.circle(x="lon", y="lat", size=8, fill_color="blue", fill_alpha=0.8, source=source, legend_label="Stations") # add hovertool for station name p.add_tools(HoverTool(tooltips=[('Station', '@Station')])) station_lat = [] station_lon = [] for line in solution.lining: route_lat = [] route_lon = [] for station in line.stations: route_lat.append(float(station.lat)) route_lon.append(float(station.lon)) station_lat.append(route_lat) station_lon.append(route_lon) # list of colors for the lines colors = [ "maroon", "deeppink", "olive", "red", "pink", "yellow", "orange", "lime", "green", "sienna", "cyan", "teal", "navy", "blue", "purple", "lavender", "magenta", "black", "dimgrey", "beige" ] # draw solution lines for i, j, k in zip(station_lon, station_lat, colors): p.line(i, j, line_width=4, line_color=k, line_alpha=0.5) output_file("visualise.html") show(p)
def draw_map(lat, lon, title="MCS"): map_options = GMapOptions(lat=0.5 * (MAX_LAT + MIN_LAT), lng=0.5 * (MAX_LON + MIN_LON), map_type="roadmap", zoom=10) p = gmap("AIzaSyDwekyNM4fOE7byChkNKCgEXklUAn3FA6o", map_options, title="MCS") source = ColumnDataSource(data=dict(lat=lat, lon=lon)) p.circle(x="lon", y="lat", size=5, fill_color="blue", fill_alpha=0.1, source=source) # export_png(p, output_dir + 'map/' + title + '.png') show(p)
from bokeh.io import output_file, show from bokeh.models import GMapOptions from bokeh.plotting import gmap output_file("gmap.html") map_options = GMapOptions(lat=30.2861, lng=-97.7394, map_type="roadmap", zoom=13) p = gmap("GOOGLE_API_KEY", map_options) show(p)
from bokeh.io import output_file, show from bokeh.models import ColumnDataSource, GMapOptions from bokeh.plotting import gmap output_file("gmap.html") map_options = GMapOptions(lat=30.2861, lng=-97.7394, map_type="roadmap", zoom=11) # For GMaps to function, Google requires you obtain and enable an API key: # # https://developers.google.com/maps/documentation/javascript/get-api-key # # Replace the value below with your personal API key: p = gmap("GOOGLE_API_KEY", map_options, title="Austin") source = ColumnDataSource( data=dict(lat=[ 30.29, 30.20, 30.29], lon=[-97.70, -97.74, -97.78]) ) p.circle(x="lon", y="lat", size=15, fill_color="blue", fill_alpha=0.8, source=source) show(p)