def populate_glyphs(self): self.plot.renderers = [] self.plot.tools = [] if self._show_counties: print "showing you the counties" #datasource = ColumnDataSource(county_data) #apatch = Patches(xs=county_xs, ys=county_ys, fill_color='white') #apatch = Patches(xs='xs', ys='ys', fill_color='colors', fill_alpha="alpha") apatch = Patches(xs='xs', ys='ys', fill_color='thecolors', fill_alpha='alpha') self.plot.add_glyph(self.county_source, apatch, name='counties') if self._show_hotels: print "showing you the hotels" circle2 = Circle(x="lon", y="lat", size=10, fill_color="fill2", fill_alpha=1.0, line_color="black") circle = Circle(x="lon", y="lat", size=10, fill_color="fill", fill_alpha=1.0, line_color="black") #print "source is ", self.source['lon'], self.source['lat'], self.source['f1ll'] self.plot.add_glyph(self.source, circle2, nonselection_glyph=circle, name='hotels') #county_xs, county_ys = get_some_counties() rndr = self.plot.renderers[-1] pan = PanTool() wheel_zoom = WheelZoomTool() box_select = BoxSelectTool() box_select.renderers = [rndr] tooltips = "@name" tooltips = "<span class='tooltip-text'>@names</span>\n<br>" tooltips += "<span class='tooltip-text'>Reviews: @num_reviews</span>" hover = HoverTool(tooltips=tooltips, names=['hotels']) tap = TapTool(names=['hotels']) self.plot.add_tools(pan, wheel_zoom, box_select, hover, tap) overlay = BoxSelectionOverlay(tool=box_select) self.plot.add_layout(overlay)
def large_plot(n): from bokeh.models import (Plot, LinearAxis, Grid, GlyphRenderer, ColumnDataSource, DataRange1d, PanTool, WheelZoomTool, BoxZoomTool, BoxSelectTool, BoxSelectionOverlay, ResizeTool, PreviewSaveTool, ResetTool) from bokeh.models.widgets.layouts import VBox from bokeh.models.glyphs import Line vbox = VBox() objects = set([vbox]) for i in xrange(n): source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1])) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr) xaxis = LinearAxis(plot=plot) yaxis = LinearAxis(plot=plot) xgrid = Grid(plot=plot, dimension=0) ygrid = Grid(plot=plot, dimension=1) tickers = [ xaxis.ticker, xaxis.formatter, yaxis.ticker, yaxis.formatter ] glyph = Line(x='x', y='y') renderer = GlyphRenderer(data_source=source, glyph=glyph) plot.renderers.append(renderer) pan = PanTool(plot=plot) wheel_zoom = WheelZoomTool(plot=plot) box_zoom = BoxZoomTool(plot=plot) box_select = BoxSelectTool(plot=plot) box_selection = BoxSelectionOverlay(tool=box_select) plot.renderers.append(box_selection) resize = ResizeTool(plot=plot) previewsave = PreviewSaveTool(plot=plot) reset = ResetTool(plot=plot) tools = [ pan, wheel_zoom, box_zoom, box_select, resize, previewsave, reset ] plot.tools.extend(tools) vbox.children.append(plot) objects |= set([ source, xdr, ydr, plot, xaxis, yaxis, xgrid, ygrid, renderer, glyph, plot.tool_events, box_selection ] + tickers + tools) return vbox, objects
hover = HoverTool() hover.tooltips = [ ("Geocoder", "@ID_list"), ] plot.add_tools(pan, wheel_zoom, box_select, hover) xaxis = LinearAxis(axis_label="Latitude", major_tick_in=0, formatter=NumeralTickFormatter(format="0.000")) plot.add_layout(xaxis, 'below') yaxis = LinearAxis(axis_label="Longitude", major_tick_in=0, formatter=PrintfTickFormatter(format="%.3f")) plot.add_layout(yaxis, 'left') overlay = BoxSelectionOverlay(tool=box_select) plot.add_layout(overlay) doc = Document() doc.add(plot) if __name__ == "__main__": filename = "maps.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Google Maps Example")) print("Wrote %s" % filename) view(filename)
def index(): # Choose from zipcode zipcode = request.form['zip code'] region_housing_data_list = [] bed_filter = [] region_housing_lo = [] region_housing_la = [] region_housing_price = [] region_house_address = [] count = 0 sum_lo = 0.0 sum_lat = 0.0 for item in housing_data_list: if item[1] == zipcode: count+=1 bed_filter.append(item) region_housing_data_list.append(item) region_housing_lo.append(item[3]) region_housing_la.append(item[2]) region_housing_price.append(item[9]) region_house_address.append(item[0]) sum_lo = sum_lo+float(item[3]) sum_lat = sum_lat+float(item[2]) elif zipcode=="": count+=1 bed_filter.append(item) region_housing_data_list.append(item) region_housing_lo.append(item[3]) region_housing_la.append(item[2]) region_housing_price.append(item[9]) region_house_address.append(item[0]) sum_lo = sum_lo+float(item[3]) sum_lat = sum_lat+float(item[2]) # Choose from number of bedroom num_beds = request.form['bedroom'] if num_beds =='0': region_housing_lo = [] region_housing_la = [] region_housing_price = [] region_house_address = [] count = 0 sum_lo = 0.0 sum_lat = 0.0 for item in region_housing_data_list: count+=1 bed_filter.append(item) region_housing_lo.append(item[3]) region_housing_la.append(item[2]) region_housing_price.append(item[9]) region_house_address.append(item[0]) sum_lo = sum_lo+float(item[3]) sum_lat = sum_lat+float(item[2]) if num_beds == '1': bed_filter = [] region_housing_lo = [] region_housing_la = [] region_housing_price = [] region_house_address = [] count = 0 sum_lo = 0.0 sum_lat = 0.0 for item in region_housing_data_list: if item[5] == 1: count+=1 bed_filter.append(item) region_housing_lo.append(item[3]) region_housing_la.append(item[2]) region_housing_price.append(item[9]) region_house_address.append(item[0]) sum_lo = sum_lo+float(item[3]) sum_lat = sum_lat+float(item[2]) elif num_beds == '2': bed_filter = [] region_housing_lo = [] region_housing_la = [] region_housing_price = [] region_house_address = [] count = 0 sum_lo = 0.0 sum_lat = 0.0 for item in region_housing_data_list: if item[5] == 2: count+=1 bed_filter.append(item) region_housing_lo.append(item[3]) region_housing_la.append(item[2]) region_housing_price.append(item[9]) region_house_address.append(item[0]) sum_lo = sum_lo+float(item[3]) sum_lat = sum_lat+float(item[2]) elif num_beds == '3+': bed_filter = [] region_housing_lo = [] region_housing_la = [] region_housing_price = [] region_house_address = [] count = 0 sum_lo = 0.0 sum_lat = 0.0 for item in region_housing_data_list: if item[5] >=3: count+=1 bed_filter.append(item) region_housing_lo.append(item[3]) region_housing_la.append(item[2]) region_housing_price.append(item[9]) region_house_address.append(item[0]) sum_lo = sum_lo+float(item[3]) sum_lat = sum_lat+float(item[2]) ## Choose from price range price_range = request.form['price_range'] if price_range =="none": pass if price_range == "0-1000": region_housing_lo = [] region_housing_la = [] region_housing_price = [] region_house_address = [] count = 0 sum_lo = 0.0 sum_lat = 0.0 for item in bed_filter: price = re.sub(r'[^0-9\.]','',item[9]) if float(price) <=1000: count+=1 region_housing_lo.append(item[3]) region_housing_la.append(item[2]) region_housing_price.append(item[9]) region_house_address.append(item[0]) sum_lo = sum_lo+float(item[3]) sum_lat = sum_lat+float(item[2]) if price_range == "1000-2000": region_housing_lo = [] region_housing_la = [] region_housing_price = [] region_house_address = [] count = 0 sum_lo = 0.0 sum_lat = 0.0 for item in bed_filter: price = re.sub(r'[^0-9\.]','',item[9]) if float(price)>1000 and float(price) <=2000: count+=1 region_housing_lo.append(item[3]) region_housing_la.append(item[2]) region_housing_price.append(item[9]) region_house_address.append(item[0]) sum_lo = sum_lo+float(item[3]) sum_lat = sum_lat+float(item[2]) if price_range == "2000-3000": region_housing_lo = [] region_housing_la = [] region_housing_price = [] region_house_address = [] count = 0 sum_lo = 0.0 sum_lat = 0.0 for item in bed_filter: price = re.sub(r'[^0-9\.]','',item[9]) if float(price)>2000 and float(price) <=3000: count+=1 region_housing_lo.append(item[3]) region_housing_la.append(item[2]) region_housing_price.append(item[9]) region_house_address.append(item[0]) sum_lo = sum_lo+float(item[3]) sum_lat = sum_lat+float(item[2]) if price_range == "3000+": region_housing_lo = [] region_housing_la = [] region_housing_price = [] region_house_address = [] count = 0 sum_lo = 0.0 sum_lat = 0.0 for item in bed_filter: price = re.sub(r'[^0-9\.]','',item[9]) if float(price) > 3000: count+=1 region_housing_lo.append(item[3]) region_housing_la.append(item[2]) region_housing_price.append(item[9]) region_house_address.append(item[0]) sum_lo = sum_lo+float(item[3]) sum_lat = sum_lat+float(item[2]) ##Drawing a google map if count == 0: region_lat = 40.7127 region_lon = -74.0059 else: region_lat = sum_lat/count region_lon = sum_lo/count y_range = Range1d() #setting ranges of the graph x_range = Range1d() map_options = GMapOptions(lat=region_lat, lng=region_lon, map_type="roadmap",zoom=13,styles=""" [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]},{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{"featureType":"road","elementType":"all","stylers":[{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]},{"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}] """ ) plot = GMapPlot( x_range=x_range, y_range=y_range, map_options=map_options, title = "NYC Housing Search" ) source = ColumnDataSource( data=dict( lon=region_housing_lo, lat=region_housing_la, Housing_Price=region_housing_price, Address = region_house_address, fill = ['blue']*len(region_housing_la) ) ) # Mouse over the markers hover = HoverTool( tooltips=[ ("Address","@Address"), ("Housing Price", "@Housing_Price"), ("location(lon,lat)", "($x, $y)"), ] ) circle = Circle(x="lon", y="lat", size=7, fill_color="fill", line_color="blue",fill_alpha=0.6) plot.add_glyph(source, circle) pan = PanTool() wheel_zoom = WheelZoomTool() box_select = BoxSelectTool() plot.add_tools(pan, wheel_zoom, box_select,hover) xaxis = LinearAxis(axis_label = "lon",major_tick_in = 0, formatter=NumeralTickFormatter(format='0.0000')) plot.add_layout(xaxis,'below') yaxis = LinearAxis(axis_label = 'lat',major_tick_in = 0, formatter = PrintfTickFormatter(format="%.4f")) plot.add_layout(yaxis, 'left') overlay = BoxSelectionOverlay(tool=box_select) # An overlay renderer that Tool objects can use to render a ¡®rubber band¡¯ selection box on a Plot. plot.add_layout(overlay) script, div = components(plot) return render_template('google_map.html',script = script, div = div)
def index(): if request.method == 'GET': return render_template('index.html') else: if request.form.get("address"): app.address = request.form['address'] else: app.address = False app.dayofweek = request.form['dayofweek'] app.direction = request.form['direction'] app.timeofday = int(request.form['timeofday']) app.ampm = request.form['ampm'] if app.address == False: app.msg = 'You must enter your desired address.' return render_template('error_page.html', msg=app.msg) params = {'address': str(app.address)} r = (requests.get('https://maps.googleapis.com/maps/api/geocode/json', params=params)).json() app.formatted_address = r['results'][0]['formatted_address'] my_latitude = r['results'][0]['geometry']['location']['lat'] my_longitude = r['results'][0]['geometry']['location']['lng'] x_min = -74.293396 #longitude SW: 40.481965, -74.293396 NE:40.911486, -73.733866 x_max = -73.733866 #longitude y_min = 40.481965 #latitude y_max = 40.911486 #latitude mesh_space = 0.01 if my_latitude < y_min or my_latitude >= y_max or my_longitude < x_min or my_longitude >= x_max or app.address == "" or app.address == False: app.msg = 'The address you entered is outside the boundaries of NYC.' return render_template('error_page.html', msg=app.msg) centers_x, centers_rx = np.linspace(x_min, x_max, (x_max - x_min) / mesh_space, retstep="True") centers_y, centers_ry = np.linspace(y_min, y_max, (y_max - y_min) / mesh_space, retstep="True") my_center_id = get_center_id(my_longitude, my_latitude, x_min=x_min, x_max=x_max, y_min=y_min, y_max=y_max, mesh_space=mesh_space) input = open( '../network_mesh_space=0.01_day=' + str(app.dayofweek) + '.pickle', 'rb') network_df = pickle.load(input) input.close() input = open( '../main_data_mesh_space=0.01_day=' + str(app.dayofweek) + '.pickle', 'rb') data_df = pickle.load(input) input.close() ################################################## ########Bokeh MAP block############################## x_range = Range1d() y_range = Range1d() # JSON style string taken from: https://snazzymaps.com/style/1/pale-dawn map_options = GMapOptions(lat=my_latitude, lng=my_longitude, map_type="roadmap", zoom=13, styles=""" [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]}, {"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]}, {"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]}, {"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]}, {"featureType":"road","elementType":"all","stylers":[{"lightness":20}]}, {"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]}, {"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]}, {"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]}, {"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}]""" ) plot = GMapPlot(x_range=x_range, y_range=y_range, map_options=map_options, title="" #plot_width=750, plot_height=750 ) plot.plot_width = 800 plot.plot_height = 800 source = ColumnDataSource(data=dict(lat=[my_latitude], lon=[my_longitude], fill=['orange', 'blue', 'green'])) circle = Circle(x="lon", y="lat", size=10, fill_color="fill", line_color="black") plot.add_glyph(source, circle) source = ColumnDataSource(data=dict( lat=[my_latitude - 0.005, my_latitude + 0.005], lon=[my_longitude - 0.005, my_longitude - 0.005], )) line = Line(x="lon", y="lat", line_width=2, line_color="green") plot.add_glyph(source, line) source = ColumnDataSource(data=dict( lat=[my_latitude + 0.005, my_latitude + 0.005], lon=[my_longitude - 0.005, my_longitude + 0.005], )) line = Line(x="lon", y="lat", line_width=2, line_color="green") plot.add_glyph(source, line) source = ColumnDataSource(data=dict( lat=[my_latitude - 0.005, my_latitude + 0.005], lon=[my_longitude + 0.005, my_longitude + 0.005], )) line = Line(x="lon", y="lat", line_width=2, line_color="green") plot.add_glyph(source, line) source = ColumnDataSource(data=dict( lat=[my_latitude - 0.005, my_latitude - 0.005], lon=[my_longitude - 0.005, my_longitude + 0.005], )) line = Line(x="lon", y="lat", line_width=2, line_color="green") plot.add_glyph(source, line) #hover.tooltips = [ #("index", "$index"), #("(x,y)", "($x, $y)"), #("radius", "@radius"), #("fill color", "$color[hex, swatch]:fill_color"), #("foo", "@foo"), #("bar", "@bar"), #] if app.ampm == "pm": app.timeofday = app.timeofday + 24 if app.direction == "from": n0 = network_df[app.timeofday][my_center_id] n0.sort(ascending=False, axis=1) n0 = n0.irow(range(20)) elif app.direction == "to": n0 = network_df[app.timeofday][:, my_center_id] n0.sort(ascending=False, axis=1) n0 = n0.irow(range(20)) #widths = [9,8,8,7,6,5,4,3,2,1] ww = 0. for index, row in n0.iteritems(): ww += 0.3 #p_i = get_center_coordinates(my_center_id,x_min=x_min, x_max=x_max, y_min=y_min, y_max=y_max,mesh_space=mesh_space) p_f = get_center_coordinates(index, x_min=x_min, x_max=x_max, y_min=y_min, y_max=y_max, mesh_space=mesh_space) ss = ColumnDataSource(data=dict( lat=[my_latitude, p_f[1]], lon=[my_longitude, p_f[0]], )) line = Line(x="lon", y="lat", line_width=ww) plot.add_glyph(ss, line) pan = PanTool() wheel_zoom = WheelZoomTool() box_select = BoxSelectTool() plot.add_tools(pan, wheel_zoom, box_select) #xaxis = LinearAxis(axis_label="lat", major_tick_in=0, formatter=NumeralTickFormatter(format="0.000")) #plot.add_layout(xaxis, 'below') #yaxis = LinearAxis(axis_label="lon", major_tick_in=0, formatter=PrintfTickFormatter(format="%.3f")) #plot.add_layout(yaxis, 'left') overlay = BoxSelectionOverlay(tool=box_select) plot.add_layout(overlay) app.script, app.div = components(plot) ################################################## ################################################## ################################################## ########Bokeh FIG block############################## # select the tools we want TOOLS = "pan,wheel_zoom,box_zoom,reset,save" #print datetime.datetime(hour=int(33)/2, minute=int(33)%2*30) #print data_df.index p1 = figure(tools=TOOLS, plot_width=400, plot_height=400, x_axis_label='Time', y_axis_label='Number of trips') #,x_axis_type='datetime') p1.line((data_df.index) / 2, data_df['number_of_pickups_at_time_slot'], line_width=2, color="blue", legend="Total number of pickups in NYC in a typical day") p1.line((data_df.index) / 2, data_df['number_of_dropoffs_at_time_slot'], line_width=2, color="red", legend="Total number of dropoffs in NYC in a typical day") #p1.circle(dates, closing_prices, fill_color="red", size=6) #plots = {'Red': p1} #script_graph1, div_graph1 = components(plots) #app.script_graph1 = script_graph1 #app.div_graph1 = div_graph1.values()[0] ################################################## ################################################## ###ADD plot of NUMBER OF TRIPS (PICK UP AND DROPOFF FROM LOCATION) pickup_count = [0 for i in range(48)] dropoff_count = [0 for i in range(48)] for ind in network_df.index.levels[0]: try: pickup_count[ind] = network_df[ind][my_center_id].count() except KeyError: pass try: dropoff_count[ind] = network_df[ind][:, my_center_id].count() except KeyError: continue TOOLS = "pan,wheel_zoom,box_zoom,reset,save" p2 = figure(tools=TOOLS, plot_width=400, plot_height=400, x_axis_label='Time', y_axis_label='Number of trips') #,x_axis_type='datetime') p2.line(np.array(range(48)) / 2, pickup_count, line_width=2, color="blue", legend="Average pickups from your location") p2.line(np.array(range(48)) / 2, dropoff_count, line_width=2, color="red", legend="Average dropoffs at your location") #p1.circle(dates, closing_prices, fill_color="red", size=6) #plots2 = {'Red': p2} plots1and2 = gridplot([[p1, p2]]) script_graph2, div_graph2 = components(plots1and2) app.script_graph2 = script_graph2 app.div_graph2 = div_graph2 return redirect('/graph_page')