def plot_distortion_bokeh(pre_poly, post_poly, dio, doi, distortion, zvalues): # plot the distortion values fig = plt.figure() plt.scatter(zvalues, distortion) plt.title('Distortion values for Rough alignment') plt.xlabel("Z") plt.ylabel("distortion") figs = figure() figs.circle(zvalues, distortion, size=5, color="navy", alpha=0.5) figs.xaxis.axis_label = "Z" figs.yaxis.axis_label = "Distortion" figs.title.text = "Distortion values for Rough alignment" grid = [] grid.append([figs, None]) for i, z in enumerate(zvalues): plot1 = figure() plot2 = figure() source1, color1 = plot_bokeh_poly(pre_poly[i]) source2, color2 = plot_bokeh_poly(post_poly[i]) glyph = Patches(xs="xs", ys="ys", fill_color="gray", fill_alpha=1.0) plot1.add_glyph(source1, glyph=glyph) glyph = Patches(xs="xs", ys="ys", fill_color="lightgray", fill_alpha=1.0) plot1.add_glyph(source2, glyph=glyph) plot1.title.text = "Alignment before and After for z={}".format(z) source3, color3 = plot_bokeh_poly(dio[i]) source4, color4 = plot_bokeh_poly(doi[i]) glyph = Patches(xs="xs", ys="ys", fill_color="red", fill_alpha=0.5) plot2.add_glyph(source3, glyph) glyph = Patches(xs="xs", ys="ys", fill_color="white", fill_alpha=1.0) plot2.add_glyph(source4, glyph) plot2.title.text = "Distortion value for z={} is {}".format( z, distortion[i]) grid.append([plot1, plot2]) grids = gridplot(grid) return grids
def altitude_profile(data): plot = Plot(plot_width=800, plot_height=400) plot.title.text = "%s - Altitude Profile" % name plot.y_range.range_padding = 0 xaxis = LinearAxis(axis_label="Distance (km)") plot.add_layout(xaxis, 'below') yaxis = LinearAxis(axis_label="Altitude (m)") plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) # x grid plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) # y grid plot.add_tools(PanTool(), WheelZoomTool(), ResetTool()) X, Y = data.dist, data.alt y0 = min(Y) patches_source = ColumnDataSource( dict(xs=[[X[i], X[i + 1], X[i + 1], X[i]] for i in range(len(X[:-1]))], ys=[[y0, y0, Y[i + 1], Y[i]] for i in range(len(Y[:-1]))], color=data.colors[:-1])) patches = Patches(xs="xs", ys="ys", fill_color="color", line_color="color") plot.add_glyph(patches_source, patches) line_source = ColumnDataSource(dict(x=data.dist, y=data.alt)) line = Line(x='x', y='y', line_color="black", line_width=1) plot.add_glyph(line_source, line) return plot
def test_Patches(): glyph = Patches() assert glyph.xs == "xs" assert glyph.ys == "ys" yield check_fill, glyph yield check_line, glyph yield check_props, glyph, ["xs", "ys"], FILL, LINE
def make_plots_traces(self): # Set up trace plots name = "traces" self.glyphs[name] = [] self.sources[name] = [] self.plots[name] = figure(plot_height=400, plot_width=800, title="Spatio-Temporal Trace", tools="pan,reset,wheel_zoom") exs, eys = self.wave_form.get_error_bar_data() self.sources["error"] = ColumnDataSource(dict(xs=exs, ys=eys)) self.glyphs["error"] = Patches(xs="xs", ys="ys", fill_alpha=0.2, line_alpha=0.0) self.plots[name].add_glyph(self.sources["error"], self.glyphs["error"]) for i, unit in enumerate(self.show_units): x, y = self.wave_form.get_template_lines(unit=unit) self.sources[name].append(ColumnDataSource(data=dict(x=x, y=y))) self.plots[name].multi_line(xs="x", ys="y", legend="# {}".format(i + 1), line_width=2, line_alpha=0.7, line_color=self.colors[i], source=self.sources[name][-1]) self.plots[name].legend.click_policy = "hide"
def plot_gmap(zones, trips=None, **map_options): """Plot zones over a Google Map. Examples: - plot_gmap(['Astoria', 'Manhattan'], zoom=12) - plot_gmap(['Astoria', 'Midtown', 'Greenpoint', 'Sunnyside', 'Harlem']) """ # Gather zone data polygons = [ GeoJSONDataSource(geojson=json.dumps(load_geojson(z))) for z in zones ] u = unary_union([load_geojson(z, make_shape=True) for z in zones]) m_polygons = u.centroid plot = GMapPlot( api_key=GOOGLE_API_KEY, x_range=Range1d(), y_range=Range1d(), map_options=GMapOptions( lat=m_polygons.y, lng=m_polygons.x, map_type="roadmap", **map_options, ), ) plot.toolbar.logo = None plot.toolbar_location = "above" plot.title.text = None # Toolbar wheel_zoom = WheelZoomTool() plot.add_tools( PanTool(), BoxZoomTool(), BoxSelectTool(), wheel_zoom, ZoomInTool(), ZoomOutTool(), ResetTool(), SaveTool(), ) plot.toolbar.active_scroll = wheel_zoom # Add neighborhood polygons for geo_source in polygons: glyph = Patches(xs="xs", ys="ys", fill_color="Blue", fill_alpha=0.2) plot.add_glyph(geo_source, glyph) # Add trips if trips is not None: add_trips_to_plot(plot, trips) output_file("plots/plot.html") show(plot) return plot
def test_Patches(): glyph = Patches() assert glyph.xs is None assert glyph.ys is None yield check_fill, glyph yield check_line, glyph yield (check_props, glyph, [ "xs", "ys", ], FILL, LINE)
def test_Patches(): glyph = Patches() assert glyph.xs is None assert glyph.ys is None check_fill_properties(glyph) check_line_properties(glyph) check_properties_existence(glyph, [ "xs", "ys", ], FILL, LINE, GLYPH)
def build_renderers(self): # parse all series. We exclude the first attr as it's the x values # added for the index glyph = Patches(xs='x_values', ys='y_values', fill_alpha=self.fill_alpha, fill_color='fill_color', line_color='line_color') renderer = GlyphRenderer(data_source=self.source, glyph=glyph) yield renderer
def test_Patches() -> None: glyph = Patches() assert glyph.xs == field("xs") assert glyph.ys == field("ys") check_fill_properties(glyph) check_hatch_properties(glyph) check_line_properties(glyph) check_properties_existence(glyph, [ "xs", "ys", ], FILL, HATCH, LINE, GLYPH)
def bokeh_map(dataframe, title='', origin_name=None, highlights=None, year=2018): output_file('test.html') df = merge_to_polygons_for_year(dataframe, year) tooltips = [ ("Postinumero:", "$pono"), ("(x,y)", "($euref_x, $euref_y)"), ] p = figure(plot_width=600, plot_height=1000, tooltips=tooltips, title=title) df_origin = df.loc[df['nimi_x'] == origin_name, :] df_highlights = df.loc[df['nimi_x'].isin(highlights), :] glyph_orig = Patches(xs="xs", ys="ys", fill_color="red") glyph_comp = Patches(xs="xs", ys="ys", fill_color="orig") p.multi_line('xs', 'ys', source=GeoJSONDataSource(geojson=df.to_json()), color='gray', line_width=0.5, alpha=0.7) p.add_glyph(GeoJSONDataSource(geojson=df_origin.to_json()), glyph_orig) p.add_glyph(GeoJSONDataSource(geojson=df_highlights.to_json()), glyph_comp) show(p)
def displayMap(): """ Method to display map and return the figure object """ x_min,y_min = -13358338.895192828, 0.0 x_max,y_max = -13326251.16329116, 26559.160710913176 url = join(basename(split(dirname(__file__))[0]), 'data/StHimarkNeighborhoodShapefile', 'StHimark.shp') stHimarkShapeFile = gpd.read_file(url) stHimarkShape = gpd.read_file(url) stHimarkShape['x'] = stHimarkShape.apply(getPolyCoords, geom='geometry', coord_type='x', axis=1) stHimarkShape['y'] = stHimarkShape.apply(getPolyCoords, geom='geometry', coord_type='y', axis=1) g_df = stHimarkShape.drop('geometry', axis=1).copy() gsource = ColumnDataSource(g_df) map_shape = figure(title="StHimark map", x_range=(x_min, x_max), y_range=(y_min,y_max)) glyph = Patches(xs= "x", ys="y", fill_alpha=0.6, fill_color='lightslategrey', line_color="black", line_width=0.1) #glyph = Patches(xs="x", ys="y", fill_color='lightslategrey') map_shape.add_glyph(gsource, glyph) map_shape.axis.visible = False map_shape.xgrid.visible = False map_shape.ygrid.visible = False return map_shape, stHimarkShapeFile, gsource
def altitude_profile(data): plot = Plot(title="%s - Altitude Profile" % title, plot_width=800, plot_height=400) xaxis = LinearAxis(axis_label="Distance (km)") plot.add_layout(xaxis, 'below') yaxis = LinearAxis(axis_label="Altitude (m)") plot.add_layout(yaxis, 'left') xgrid = Grid(plot=plot, dimension=0, ticker=xaxis.ticker) ygrid = Grid(plot=plot, dimension=1, ticker=yaxis.ticker) plot.renderers.extend([xgrid, ygrid]) plot.add_tools(PanTool(), WheelZoomTool(), ResetTool(), BoxSelectTool()) X, Y = data.dist, data.alt y0 = min(Y) patches_source = ColumnDataSource( dict(xs=[[X[i], X[i + 1], X[i + 1], X[i]] for i in range(len(X[:-1]))], ys=[[y0, y0, Y[i + 1], Y[i]] for i in range(len(Y[:-1]))], color=data.colors[:-1])) patches = Patches(xs="xs", ys="ys", fill_color="color", line_color="color") plot.add_glyph(patches_source, patches) line_source = ColumnDataSource(dict( x=data.dist, y=data.alt, )) line = Line(x='x', y='y', line_color="black", line_width=1) plot.add_glyph(line_source, line) plot.x_range = DataRange1d() plot.y_range = DataRange1d() return plot
def drawOnFigure(fig, source, raw_data, nodes, data_format): # Load example data data = readData(raw_data, nodes, data_format) data[data_format['xs'] + '_shown'] = [] data[data_format['ys'] + '_shown'] = [] data[data_format['vs'] + '_shown'] = [] data[data_format['cs'] + '_shown'] = [] data[data_format['as'] + '_shown'] = [] source.data = data # Plot patches to figure glyph = Patches(xs=data_format['xs'] + "_shown", ys=data_format['ys'] + "_shown", fill_color=data_format['cs'] + "_shown", fill_alpha=data_format['as'] + "_shown", line_width=0, line_color=None) # Add patch glyph to figure fig.add_glyph(source, glyph)
"""catchment polygons """ catchmentmap_df = boundary[[ 'Basin_ID', 'Watershed', "Area_km2", "x", "y", "colors", "legend" ]] catchmentmap_dfsource = ColumnDataSource(data=catchmentmap_df) #Add polygon grid and a legend for it # patch for the normal graph #grid=catchmentmap_intro_page.patches("x","y", source=catchmentmap_dfsource, name="grid", ## fill_color={"field":"color"}, # fill_alpha=1.0, line_color="black", line_width=0.03, legend="label_pt") # patch for the catchment polygon catchmentmap_intro_page_patches = Patches(xs="x", ys="y", fill_color="colors", fill_alpha=0.1, line_color="black", line_width=2) catchmentmap_intro_page_glyph = catchmentmap_intro_page.add_glyph( catchmentmap_dfsource, catchmentmap_intro_page_patches) # TODO add legend # tools Polygon_hover = HoverTool(renderers=[catchmentmap_intro_page_glyph]) #Polygon_hover = catchmentmap_intro_page .select(dict(type=HoverTool)) Polygon_hover.tooltips = OrderedDict([('Basin ID', '@Basin_ID'), ('Catchment Name', '@Watershed'), ("Area (km2)", "@Area_km2"), ("(long)", "$x,"), ("lat", (" $y"))]) """mark at the rainfall station""" # don't but the rainfall_station instead it will make an error as it has geometry column rainfall_station_source = ColumnDataSource(
def map_viz_tab(): def plot_sensor_path(sensors, df_final): for i in sensors: #plotter.line(x=path_data.get_group(i).x, y=path_data.get_group(i).y, name=str(i), color="black") plotter.line(x=df_final['x'].loc[df_final['sid'] == i], y=df_final['y'].loc[df_final['sid'] == i], color="orange") def updateOverlays(attr, old, new): overlays = checkbox_btn_group.active if 0 in overlays: img_hsp = "https://upload.wikimedia.org/wikipedia/commons/d/d0/Flag_for_hospital_ship_of_the_Regia_Marina.svg" hospital_data = dict(url=[img_hsp] * 8, x=df_hospitalLocation.x, y=df_hospitalLocation.y) source_hospital.data = hospital_data else: h_x, h_y, h_url = [], [], [] hospital_data = dict(url=h_url, x=h_x, y=h_y) source_hospital.data = hospital_data if 1 in overlays: x_patch, y_patch, x_vor_ls, y_vor_ls = get_voronoi( df_hospitalLocation.x, df_hospitalLocation.y) patch_data = dict(xs=x_patch, ys=y_patch) lines_data = dict(xs=x_vor_ls, ys=y_vor_ls) source_vor.data = patch_data source_vor_ls.data = lines_data else: x_patch, y_patch, x_vor_ls, y_vor_ls = [], [], [], [] patch_data = dict(xs=x_patch, ys=y_patch) lines_data = dict(xs=x_vor_ls, ys=y_vor_ls) source_vor.data = patch_data source_vor_ls.data = lines_data if 2 in overlays: color_mapper = LinearColorMapper(palette=palette, low=0, high=50) mp.fill_color = {'field': 'Value', 'transform': color_mapper} mp.fill_alpha = 1.0 tick_labels = { '0': '0', '10': '10', '20': '20', '30': '30', '40': '40', '50': '>50' } color_bar = ColorBar(color_mapper=color_mapper, label_standoff=5, width=500, height=20, border_line_color=None, location=(0, 0), orientation='horizontal', major_label_overrides=tick_labels) plotter.add_layout(color_bar, 'below') else: mp.fill_color = 'lightslategrey' mp.fill_alpha = 0.5 def updateMotionMap(attr, old, new): check = checkbox_btn_group1.active xmin = -13326251 if 0 in check: img_state = [ "https://i.imgur.com/IBpHIs1.png", "https://i.imgur.com/oawpbdU.png", "https://i.imgur.com/kigeppa.png", "https://i.imgur.com/mHAUX9K.png", "https://i.imgur.com/pxbaYlp.png", "https://i.imgur.com/QNhcnRn.png", "https://i.imgur.com/GB2fRMS.png", "https://i.imgur.com/qXfEJNL.png", "https://i.imgur.com/QZOTgG9.png", "https://i.imgur.com/sE1U89y.png", "https://i.imgur.com/vAxwSQE.png", "https://i.imgur.com/yO1iOCw.png", "https://i.imgur.com/jFpJ2UQ.png", "https://i.imgur.com/lVkwzYH.png", "https://i.imgur.com/Q519cud.png", "https://i.imgur.com/FtnTUAC.png", "https://i.imgur.com/j2D9ud6.png", "https://i.imgur.com/Tb4tWI5.png", "https://i.imgur.com/yhl5nAX.png" ] states_x = [ xmin - 28000, xmin - 22500, xmin - 16000, xmin - 12000, xmin - 22000, xmin - 22500, xmin - 1000, xmin - 6000, xmin - 14000, xmin - 8000, xmin - 4700, xmin - 4700, xmin - 9000, xmin - 16000, xmin - 19500, xmin - 19500, xmin - 14000, xmin - 13000, xmin - 16500 ] states_y = [ 19000, 19700, 20000, 17000, 12000, 16000, 11000, 3800, 6000, 5900, 7000, 10500, 12500, 17000, 17000, 13500, 9200, 13500, 13000 ] w = [ 4000, 5000, 4000, 4000, 4000, 4000, 3000, 4800, 5000, 2500, 4000, 4000, 4000, 3000, 3000, 3000, 4300, 3500, 3500 ] h = [ 3600, 3000, 3000, 3000, 3000, 3000, 6000, 4800, 3000, 5000, 4000, 3000, 4000, 2000, 2000, 3000, 2700, 3500, 3500 ] states_data = dict(url=img_state, x=states_x, y=states_y, w=w, h=h) source_states.data = states_data else: h_x, h_y, h_url, w, h = [], [], [], [], [] states_data = dict(url=h_url, x=h_x, y=h_y, w=w, h=h) source_states.data = states_data if 1 in check: source_path1.data = data_path1 else: source_path1.data = data_path def update_time_frame(attr, old, new): """ update the time frame and load new dataframes """ timeline.value = time_start time_current = time_start if time_frame.active == 0: timeline.step = 5 df_mobile_location_cur = df_mobileLocation_raw df_static_reading_cur = df_staticSensors_raw df_mobile_reading_cur = df_mobileSensors_raw if time_frame.active == 1: timeline.step = 60 df_mobile_location_cur = df_mobileLocation_min df_static_reading_cur = df_staticSensors_min df_mobile_reading_cur = df_mobileSensors_min if time_frame.active == 2: timeline.step = 3600 df_mobile_location_cur = df_mobileLocation_hr df_static_reading_cur = df_staticSensors_hr df_mobile_reading_cur = df_mobileSensors_hr static_sensors_update(attr, old, new) mobile_sensors_update(attr, old, new) def getDFfromDB(table_name): url = join(basename(split(dirname(__file__))[0]), 'data', 'StHimarkDB.db') conn = sq.connect(url) df = pd.read_sql_query("select * from " + table_name + ";", conn) return df def static_sensors_update(attr, old, new): time_current = datetime.fromtimestamp(timeline.value + baseTime) sid, x, y, val, user = [], [], [], [], [] data_new = collections.OrderedDict({ 'sid': sid, 'x_loc': x, 'y_loc': y, 'value': val, 'user': user, }) source_static.data = data_new #clean(source_static_locations) selected = static_sensors_ms.value selectedStaticSensors.clear() for name in selected: selectedStaticSensors.append(name.split("_", 1)[1]) for sensor in selectedStaticSensors: sid.append(sensor) x.append(df_staticLocation['x'].loc[df_staticLocation['sid'] == int(sensor)].values.item()) y.append(df_staticLocation['y'].loc[df_staticLocation['sid'] == int(sensor)].values.item()) val.append(df_static_reading_cur[sensor].loc[ df_static_reading_cur['Timestamp'] == time_current].values.item()) user.append('Sensor ' + sensor) data_new = collections.OrderedDict({ 'sid': sid, 'x_loc': x, 'y_loc': y, 'value': val, 'user': user, }) source_static.data = data_new def mobile_sensors_update(attr, old, new): time_current = datetime.fromtimestamp(timeline.value + baseTime) greencar = 'https://i.imgur.com/YyWzmgH.png' selected = mobile_sensors_ms.value overlays = checkbox_btn_group.active path_flag = False if 3 in overlays: path_flag = True selectedMobileSensors.clear() sid,x,y,clr,val,user, x_path, y_path,img=[],[],[],[],[],[],[],[],[] data_new_mobile = collections.OrderedDict({ 'sid': sid, 'x_loc': x, 'y_loc': y, 'colo': clr, 'value': val, 'user': user, 'url': img, }) source_mobile.data = data_new_mobile df_path = pd.DataFrame(columns=['sid', 'x', 'y']) data_path = collections.OrderedDict({ 'x_path': x_path, 'y_path': y_path, }) source_path.data = data_path safety_thresh = safe_threshold.value for name in selected: selectedMobileSensors.append(name.split("_", 1)[1]) img = [greencar] * len(selectedMobileSensors) for sensor in selectedMobileSensors: col_x = '(\'x\', \'{}\')'.format(sensor) col_y = '(\'y\', \'{}\')'.format(sensor) sid.append(sensor) x.append(df_mobile_location_cur[col_x].loc[ df_mobile_location_cur['Timestamp'] == time_current].values.item()) y.append(df_mobile_location_cur[col_y].loc[ df_mobile_location_cur['Timestamp'] == time_current].values.item()) val1 = df_mobile_reading_cur[sensor].loc[ df_mobile_reading_cur['Timestamp'] == time_current].values.item() if val1 == None: val1 = 0 user.append(df_mobileUsers['user'].loc[df_mobileUsers['sensor'] == int(sensor)].values.item()) if int(float(val1)) > safety_thresh: clr.append('darkred') #clr.append(redcar) else: clr.append('lawngreen') #clr.append(greencar) val.append(val1) #clr.append(RGB( 255 - int(sensor), (int(sensor)*2)+50, int(sensor)*4)) if path_flag == True: df_temp = pd.DataFrame() df_temp['x'] = df_mobile_location_cur[col_x] df_temp['y'] = df_mobile_location_cur[col_y] df_temp['sid'] = sensor df_path = df_path.append(df_temp) data_new_mobile = collections.OrderedDict({ 'sid': sid, 'x_loc': x, 'y_loc': y, 'colo': clr, 'value': val, 'user': user, 'url': img, }) source_mobile.data = data_new_mobile if path_flag == True: data_path = collections.OrderedDict({ 'x_path': [ df_path['x'].loc[df_path['sid'] == i] for i in selectedMobileSensors ], 'y_path': [ df_path['y'].loc[df_path['sid'] == i] for i in selectedMobileSensors ], }) source_path.data = data_path #df_path.to_csv('total_path.csv', index=None, header=True) #path_data = df_path.groupby('sid') #plot_sensor_path(selectedMobileSensors, df_path) def update_safeT(attr, old, new): global safety_thresh safety_thresh = safe_threshold.value def update_time(attr, old, new): greencar = 'https://i.imgur.com/YyWzmgH.png' safety_thresh = safe_threshold.value time_current = datetime.fromtimestamp(timeline.value + baseTime) text = template.format(curTime=time_current) label.text = str(time_current) some_div.text = text sid, x, y, clr, val, user, img = [], [], [], [], [], [], [] if 2 in checkbox_btn_group.active: radiationFlag = True else: radiationFlag = False if radiationFlag == True: time1 = str(time_current) new_data3 = json_data(time1) geosource.geojson = new_data3 data_new_mobile = collections.OrderedDict({ 'sid': sid, 'x_loc': x, 'y_loc': y, 'colo': clr, 'value': val, 'user': user, 'url': img, }) source_mobile.data = data_new_mobile data_new_static = collections.OrderedDict({ 'sid': sid, 'x_loc': x, 'y_loc': y, 'value': val, 'user': user, }) source_static.data = data_new_static img = [greencar] * len(selectedMobileSensors) for sensor in selectedMobileSensors: col_x = '(\'x\', \'{}\')'.format(sensor) col_y = '(\'y\', \'{}\')'.format(sensor) sid.append(sensor) x.append(df_mobile_location_cur[col_x].loc[ df_mobile_location_cur['Timestamp'] == time_current].values.item()) y.append(df_mobile_location_cur[col_y].loc[ df_mobile_location_cur['Timestamp'] == time_current].values.item()) val1 = df_mobile_reading_cur[sensor].loc[ df_mobile_reading_cur['Timestamp'] == time_current].values.item() if val1 == None: val1 = 0 if int(float(val1)) > safety_thresh: clr.append('red') #clr.append(redcar) else: clr.append('green') #clr.append(greencar) #clr.append(RGB( 255 - int(sensor), (int(sensor)*2)+50, int(sensor)*4)) val.append(val1) user.append(df_mobileUsers['user'].loc[df_mobileUsers['sensor'] == int(sensor)].values.item()) data_new_mobile = collections.OrderedDict({ 'sid': sid, 'x_loc': x, 'y_loc': y, 'colo': clr, 'value': val, 'user': user, 'url': img, }) source_mobile.data = data_new_mobile x, y, val, user, sid = [], [], [], [], [] for sensor in selectedStaticSensors: sid.append(sensor) x.append(df_staticLocation['x'].loc[df_staticLocation['sid'] == int(sensor)].values.item()) y.append(df_staticLocation['y'].loc[df_staticLocation['sid'] == int(sensor)].values.item()) val.append(df_static_reading_cur[sensor].loc[ df_static_reading_cur['Timestamp'] == time_current].values.item()) user.append('Sensor ' + sensor) data_new_static = collections.OrderedDict({ 'sid': sid, 'x_loc': x, 'y_loc': y, 'value': val, 'user': user, }) source_static.data = data_new_static def clearStaticSensors(): sid, x, y, clr, val, user = [], [], [], [], [], [] static_sensors_ms.value = [] data_new_static = collections.OrderedDict({ 'sid': sid, 'x_loc': x, 'y_loc': y, 'value': val, 'user': user, }) source_static.data = data_new_static def clearMobileSensors(): mobile_sensors_ms.value = [] sid,x,y,clr,val,user, x_path, y_path,img=[],[],[],[],[],[],[],[],[] data_path = collections.OrderedDict({ 'x_path': x_path, 'y_path': y_path, }) source_path.data = data_path data_new_mobile = collections.OrderedDict({ 'sid': sid, 'x_loc': x, 'y_loc': y, 'colo': clr, 'value': val, 'user': user, 'url': img, }) source_mobile.data = data_new_mobile def animate_update(): time_current = timeline.value + timeline.step if time_current > time_end: time_current = time_start timeline.value = time_current update_time(None, None, None) def animate(): global callback_id if btn_animate.label == '► Play': btn_animate.label = '❚❚ Pause' callback_id = curdoc().add_periodic_callback(animate_update, 200) else: btn_animate.label = '► Play' curdoc().remove_periodic_callback(callback_id) def json_data(timestamp): #time = df_hour_data['Timestamp'].loc[df_hour_data['Timestamp'] ==timestamp] time1 = pd.to_datetime(timestamp) time1 = time1.replace(minute=0, second=0) timestamp = str(time1.to_pydatetime()) df_temp = df_hour_data_group.get_group(timestamp) merged = stHimarkShape.merge(df_temp, left_on='Nbrhood', right_on='Neighbourhood', how='left') merged_json = json.loads(merged.to_json()) return json.dumps(merged_json) #Declare all the variables and datasources here plotter, stHimarkShape, gsource = displayMap() selectedStaticSensors, selectedMobileSensors = [], [] time_start = 0 time_end = 1 time_current = 0 safety_thresh = 40 #Get Dataframe for static sensors sid,x,y,clr,val,user,x_path, y_path, img=[],[],[],[],[],[],[],[],[] data_static = collections.OrderedDict({ 'sid': sid, 'x_loc': x, 'y_loc': y, 'value': val, }) source_static = ColumnDataSource(data=data_static) data_mobile = collections.OrderedDict({ 'sid': sid, 'x_loc': x, 'y_loc': y, 'colo': clr, 'value': val, 'user': user, 'url': img, }) source_mobile = ColumnDataSource(data=data_mobile) data_path = collections.OrderedDict({ 'x_path': [x_path], 'y_path': [y_path], }) source_path = ColumnDataSource(data=data_path) url = join(basename(split(dirname(__file__))[0]), 'data', 'total_path.csv') df_tp = pd.read_csv(url) data_path1 = collections.OrderedDict({ 'x_path': [df_tp['x'].loc[df_tp['sid'] == i] for i in range(1, 51)], 'y_path': [df_tp['y'].loc[df_tp['sid'] == i] for i in range(1, 51)], }) source_path1 = ColumnDataSource(data=data_path) df_staticSensors_hr = getDFfromDB("StaticSensorReading_hours") df_mobileSensors_hr = getDFfromDB("MobileSensorReading_hours") df_staticSensors_min = getDFfromDB("StaticSensorReading_minutes") df_mobileSensors_min = getDFfromDB("MobileSensorReading_minutes") df_staticSensors_raw = getDFfromDB("StaticSensorReading_raw") df_mobileSensors_raw = getDFfromDB("MobileSensorReading_raw") df_staticLocation = getDFfromDB("StaticSensorLocation") df_hospitalLocation = getDFfromDB("HospitalLocation") df_mobileLocation_hr = getDFfromDB("MobileSensorLocation_hours") df_mobileLocation_min = getDFfromDB("MobileSensorLocation_minutes") df_mobileLocation_raw = getDFfromDB("MobileSensorLocation_raw") #read mobile sensor users data url = join(basename(split(dirname(__file__))[0]), 'data', 'mobileuser.csv') df_mobileUsers = pd.read_csv(url) df_mobileLocation_hr['Timestamp'] = pd.to_datetime( df_mobileLocation_hr['Timestamp']) df_mobileLocation_min['Timestamp'] = pd.to_datetime( df_mobileLocation_min['Timestamp']) df_mobileLocation_raw['Timestamp'] = pd.to_datetime( df_mobileLocation_raw['Timestamp']) df_mobileSensors_hr['Timestamp'] = pd.to_datetime( df_mobileSensors_hr['Timestamp']) df_mobileSensors_min['Timestamp'] = pd.to_datetime( df_mobileSensors_min['Timestamp']) df_mobileSensors_raw['Timestamp'] = pd.to_datetime( df_mobileSensors_raw['Timestamp']) df_staticSensors_hr['Timestamp'] = pd.to_datetime( df_staticSensors_hr['Timestamp']) df_staticSensors_min['Timestamp'] = pd.to_datetime( df_staticSensors_min['Timestamp']) df_staticSensors_raw['Timestamp'] = pd.to_datetime( df_staticSensors_raw['Timestamp']) df_static_reading_cur = df_staticSensors_raw df_mobile_reading_cur = df_mobileSensors_raw df_mobile_location_cur = df_mobileLocation_raw #Radiation Map url = join(basename(split(dirname(__file__))[0]), 'data', 'df_hour_combined.csv') df_hour_data = pd.read_csv(url) df_hour_data_group = df_hour_data.groupby('Timestamp') time = df_hour_data['Timestamp'][0] df_first = df_hour_data_group.get_group(time) merged = stHimarkShape.merge(df_first, left_on='Nbrhood', right_on='Neighbourhood') static_list = [1, 4, 6, 9, 11, 12, 13, 14, 15] mobile_list = list(range(1, 51)) static_sensor_list = {} mobile_sensor_list = {} for sensor in static_list: static_sensor_list.update({int(sensor): "Sensor_" + str(sensor)}) for sensor in mobile_list: mobile_sensor_list.update({int(sensor): "Sensor_" + str(sensor)}) static_sensor_list = collections.OrderedDict( sorted(static_sensor_list.items())) mobile_sensor_list = collections.OrderedDict( sorted(mobile_sensor_list.items())) df_staticSensors_hr['Timestamp'] = pd.to_datetime( df_staticSensors_hr['Timestamp']) time_start = df_staticSensors_hr['Timestamp'][0] time_current = time_start time_end = df_staticSensors_hr['Timestamp'][len(df_staticSensors_hr.index) - 1] baseTime = datetime.timestamp(time_start) time_start = datetime.timestamp(time_start) - baseTime time_end = datetime.timestamp(time_end) - baseTime #Widget: Multiselect --- Create two multiselect widgets for static and mobile sensors static_sensors_ms = MultiSelect(title="Static Sensors:", options=list(static_sensor_list.values()), height=250) static_sensors_ms.on_change('value', static_sensors_update) mobile_sensors_ms = MultiSelect(title="Mobile Sensors:", options=list(mobile_sensor_list.values()), height=250) mobile_sensors_ms.on_change('value', mobile_sensors_update) controls = WidgetBox(row([static_sensors_ms, mobile_sensors_ms])) btn_staticClear = Button(label='Clear Static Selection') btn_mobileClear = Button(label='Clear Mobile Selection') btn_staticClear.on_click(clearStaticSensors) btn_mobileClear.on_click(clearMobileSensors) btn_group = WidgetBox( row([ WidgetBox(btn_staticClear, width=310), WidgetBox(btn_mobileClear, width=310) ])) overlay_div = Div(text='<b>Map Overlays</b>', style={ 'font-size': '120%', 'color': 'black' }) checkbox_btn_group = CheckboxButtonGroup(labels=[ 'Show Hospitals', 'Hospital Vornoi Map', 'Radiation Map', 'Trace Paths' ], active=[]) checkbox_btn_group.on_change('active', updateOverlays) checkbox_btn_group1 = CheckboxButtonGroup( labels=['State Labels', 'Trace Motion Map'], active=[]) checkbox_btn_group1.on_change('active', updateMotionMap) timeframe_div = Div(text='<b>Time Frame</b>', style={ 'font-size': '120%', 'color': 'black' }) time_frame = RadioButtonGroup(labels=["Raw", "By Minutes", "By Hours"], active=0, name="Sort By:") time_frame.on_change('active', update_time_frame) template = (""" <b>Timestamp: </b> <span class='number'>{curTime}</span> """) text = template.format(curTime=time_current) some_div = Div(text=text, style={'font-size': '100%', 'color': 'black'}) timeline = Slider(title="", value=0, start=time_start, end=time_end, step=5) timeline.show_value = False timeline.on_change('value', update_time) btn_animate = Button(label='► Play', width=180) btn_animate.on_click(animate) x_patch, y_patch, x_vor_ls, y_vor_ls = [], [], [], [] patch_data = dict(xs=x_patch, ys=y_patch) lines_data = dict(xs=x_vor_ls, ys=y_vor_ls) source_vor = ColumnDataSource() source_vor_ls = ColumnDataSource() source_vor.data = patch_data source_vor_ls.data = lines_data h_x, h_y, h_url = [], [], [] hospital_data = dict(url=h_url, x=h_x, y=h_y) source_hospital = ColumnDataSource() source_hospital.data = hospital_data w_s, h_s = [], [] states_data = dict(url=h_url, x=h_x, y=h_y, w=w_s, h=h_s) source_states = ColumnDataSource() source_states.data = states_data palette = brewer['RdYlGn'][5] color_mapper = LinearColorMapper(palette=palette, low=0, high=50) merged_json = json.loads(merged.to_json()) json_data1 = json.dumps(merged_json) geosource = GeoJSONDataSource(geojson=json_data1) tick_labels = { '0': '0', '10': '10', '20': '20', '30': '30', '40': '40', '50': '>50' } color_bar = ColorBar(color_mapper=color_mapper, label_standoff=5, width=500, height=20, border_line_color=None, location=(0, 0), orientation='horizontal', major_label_overrides=tick_labels) plotter.add_layout(color_bar, 'below') mp = Patches(xs='xs', ys='ys', fill_color='lightslategrey', line_color="black", line_width=0.05, fill_alpha=0.5) plotter.add_glyph(geosource, mp) plotter.patches('xs', 'ys', source=source_vor, alpha=0.3, line_width=1, fill_color='lightslategrey', line_color='black') plotter.multi_line('xs', 'ys', source=source_vor_ls, alpha=1, line_width=1, line_color='black') safe_threshold = Slider(title="Safety Threshold(In cpm)", value=safety_thresh, start=0, end=100, step=1) safe_threshold.on_change('value', update_safeT) layout = column( row([ plotter, column([ controls, btn_group, overlay_div, checkbox_btn_group, checkbox_btn_group1, timeframe_div, time_frame, row([some_div, btn_animate]), timeline, safe_threshold ]) ])) glyph = MultiLine(xs="x_path", ys="y_path", line_color="saddlebrown", line_width=0.8, line_alpha=0.5) plotter.add_glyph(source_path1, glyph) glyph = MultiLine(xs="x_path", ys="y_path", line_color="darkred", line_width=2, line_alpha=0.9) plotter.add_glyph(source_path, glyph) image1 = ImageURL(url='url', x="x", y="y", w=600, h=600, anchor="center") plotter.add_glyph(source_hospital, image1) image_states = ImageURL(url='url', x="x", y="y", w="w", h="h", anchor="center") plotter.add_glyph(source_states, image_states) label = Label(x=-13358000, y=2000, text=str(time_current), text_font_size='20pt', text_color='yellowgreen') plotter.add_layout(label) plotter.hex(name="static_hover", x='x_loc', y='y_loc', color="yellow", size=12, alpha=1, source=source_static) carimage = ImageURL(url='url', x='x_loc', y='y_loc', w=600, h=1100, anchor='center') plotter.add_glyph(source_mobile, carimage) plotter.circle(name="dynamic_hover", x='x_loc', y='y_loc', fill_color='colo', line_color='colo', size=6, alpha=1, source=source_mobile) hover = HoverTool(names=["static_hover", "dynamic_hover"], tooltips=[("Sensor", "@sid"), ("Radiation", "@value"), ("User", "@user")], show_arrow=False) plotter.tools = [hover] #plotter.diamond(x='x', y ='y', color='green',size=15, source = source_hospital) img_path = "https://upload.wikimedia.org/wikipedia/commons/b/b8/Nuclear_plant.svg" plotter.image_url(url=[img_path], x=-13334385.723761385, y=18109.34344275895, w=1000, h=1000, anchor='center') tab = Panel(child=layout, title='Visual Analysis') return tab
fill_color='red', line_color='red', legend_label='deaths') p.scatter('x', 'y', 'size', source=map_source_recovered, fill_alpha=0.3, line_alpha=1, fill_color='green', line_color='green', legend_label='recovered') glyph = Patches(xs="xs", ys="ys", fill_alpha="fill_alpha", fill_color="fill_color", line_color=None) p.add_glyph(US_map_source_confirmed, glyph) p.legend.click_policy = "hide" timeslider = Slider(start=1, end=numDays, value=numDays, step=1, title="Days since data collection") timeslider.on_change('value', update_data) playbutton = Button(label="► Play", button_type="success") timeline = range(timeslider.end) #citation = Label(text=f"{latestDateCol}", x=70, y=70, x_units='screen', y_units='screen', render_mode='css', # border_line_color='black', border_line_alpha=1.0,
def show_data(self): """ Setup plots and commit them into the layout. """ # Plot map tools = "pan,wheel_zoom,box_zoom,reset,tap,save" p = figure( width=800, height=600, title="", tools=tools, x_range=(-2.45 * 10 ** 6, 5.12 * 10 ** 6), y_range=(3.73 * 10 ** 6, 1.13 * 10 ** 7) ) p.title.text_font_size = "25px" p.title.align = "center" p.toolbar.logo = None # Set Tiles tile_source = WMTSTileSource( url='https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg' ) p.add_tile(tile_source) p.axis.visible = False # print(self.lvl_geodata['Level 3'].data) color_mapper = LogColorMapper(palette=palette) glyphs = p.patches( 'x', 'y', source=self.current_map_CDS, fill_color={'field': 'classified', 'transform': color_mapper}, fill_alpha=0.5, line_color="black", line_width=0.3 ) glyphs.nonselection_glyph = Patches( fill_alpha=0.2, line_width=0.3, fill_color={'field': 'classified', 'transform': color_mapper} ) glyphs.selection_glyph = Patches( fill_alpha=0.8, line_width=0.8, fill_color={'field': 'classified', 'transform': color_mapper} ) glyphs.hover_glyph = Patches( line_width=1, fill_color={'field': 'classified', 'transform': color_mapper} ) # set the callback for the tap tool glyphs.data_source.on_change('selected', self.tap_callback) hover = HoverTool() hover.tooltips = [('NUTS_ID', '@NUTS_ID'), ('Indicator', '@observation')] p.add_tools(hover) p2 = Paragraph(text="No data selected. Please select region.") self.layout.children[1] = column([row(self.id_select), row(self.lvl_select, self.year_select), p]) self.layout.children[2] = column(p2) self.set_new_year_selector()
def getStatesPlot(df): init_sources = get_Sources(df) str_sources = {} dictionary_of_sources = {} for year in init_sources.keys(): str_sources['_' + str(year)] = assignStateColors(init_sources[year]) dictionary_of_sources[year] = '_' + str(year) jssources = str(dictionary_of_sources).replace("'", "") renderer_source = str_sources['_2006'] hover = HoverTool(tooltips=[("State", "@names"), ("Funds", "@funds"), ('Hit By', "@hitby")]) p = figure(title="Funding Given Per Hurricane", toolbar_location="left", tools=[hover], plot_width=900, plot_height=500) p.xgrid.visible = False p.ygrid.visible = False p.xaxis.visible = False p.yaxis.visible = False state_glyph = Patches(xs='x', ys='y', fill_alpha=0.5, fill_color='color', line_color="#884444", line_width=1, line_alpha=1) jscode = """var year = slider.get('value'), sources = %s, new_source_data = sources[year].get('data'); renderer_source.set('data', new_source_data); """ % jssources callback = CustomJS(args=str_sources, code=jscode) slider = Slider(start=2005, end=2017, step=1, value=2006, title='Year', callback=callback) callback.args["renderer_source"] = renderer_source callback.args["slider"] = slider text_x = -135 text_y = 50 funds = ['< 10 M', '< 100 M', '< 500 M', '< 1 B', '< 5 B', '> 5 B'][::-1] colored = [0, 2, 3, 4, 6, 8] p.add_glyph( Text(x=text_x - 2, y=text_y + 2, text=['Amount of Funds Raised'], text_font_size='10pt', text_color='#666666', text_align='left')) for i, fund in enumerate(funds): p.add_glyph( Text(x=text_x + 1, y=text_y, text=[fund], text_font_size='10pt', text_color='#666666', text_align='left')) p.add_glyph( Circle(x=text_x, y=text_y + 0.4, fill_color=Greens9[colored[i]], size=15, line_color=None, fill_alpha=0.8)) text_y = text_y - 2 p.add_glyph(renderer_source, state_glyph) return slider, p
url=dict( value="http://bokeh.pydata.org/en/latest/_static/images/logo.png" ), anchor="center")), ("line", Line(x="x", y="y", line_color="#F46D43")), ("multi_line", MultiLine(xs="xs", ys="ys", line_color="#8073AC", line_width=2)), ("oval", Oval(x="x", y="y", width=screen(15), height=screen(25), angle=-0.7, fill_color="#1D91C0")), ("patch", Patch(x="x", y="y", fill_color="#A6CEE3")), ("patches", Patches(xs="xs", ys="ys", fill_color="#FB9A99")), ("quad", Quad(left="x", right="xp01", top="y", bottom="ym01", fill_color="#B3DE69")), ("quadratic", Quadratic(x0="x", y0="y", x1="xp02", y1="y", cx="xp01", cy="yp01", line_color="#4DAF4A", line_width=3)), ("ray", Ray(x="x", y="y",
)) xdr = DataRange1d(sources=[source.columns("xs")]) ydr = DataRange1d(sources=[source.columns("ys")]) plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=300, plot_height=300, h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None) glyph = Patches(xs="xs", ys="ys", fill_color="#fb9a99") plot.add_glyph(source, glyph) xaxis = LinearAxis() plot.add_layout(xaxis, 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) doc = Document() doc.add(plot) show(plot)
y_range=Range1d(), # border_fill = '#130f30', map_options=GMapOptions(lat=52.521123, lng=13.407478, zoom=10)) # tools="pan,wheel_zoom,box_zoom,reset,hover,save") p.map_options.map_type = "terrain" # satellite, roadmap, terrain or hybrid source_patches = bk.ColumnDataSource(data=dict(boroughs_xs=boroughs_xs, boroughs_ys=boroughs_ys, boroughs_colors=boroughs_colors, boroughsnames=boroughsnames, population=population, area=area, density=density)) patches = Patches(xs="boroughs_xs", ys="boroughs_ys", fill_color="boroughs_colors", fill_alpha=0.7, line_color="black", line_width=0.5) patches_glyph = p.add_glyph(source_patches, patches) p.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool(), HoverTool(), ResetTool(), PreviewSaveTool()) #xaxis = LinearAxis(axis_label="lat", major_tick_in=0, formatter=NumeralTickFormatter(format="0.000")) #p.add_layout(xaxis, 'below') #yaxis = LinearAxis(axis_label="lon", major_tick_in=0, formatter=PrintfTickFormatter(format="%.3f")) #p.add_layout(yaxis, 'left') hover = p.select(dict(type=HoverTool)) #hover.snap_to_data = False # not supported in new bokeh versions hover.tooltips = OrderedDict([
xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr, min_border=0, border_fill_color="white", title="2009 Unemployment Data", plot_width=1300, plot_height=800, toolbar_location="left") county_patches = Patches(xs="county_xs", ys="county_ys", fill_color="county_colors", fill_alpha=0.7, line_color="white", line_width=0.5) plot.add_glyph(county_source, county_patches) state_patches = Patches(xs="state_xs", ys="state_ys", fill_alpha=0.0, line_color="#884444", line_width=2) plot.add_glyph(state_source, state_patches) plot.add_tools(ResizeTool()) doc = Document() doc.add_root(plot)
#Instantiate LinearColorMapper that linearly maps numbers in a range, into a sequence of colors. color_mapper = LinearColorMapper(palette = palette, low = 0, high = 2500000, nan_color = '#d9d9d9') #Define custom tick labels for color bar. tick_labels = {'0': '0%', '5': '5%', '10':'10%', '15':'15%', '20':'20%', '25':'25%', '30':'30%','35':'35%', '40': '>40%'} #Add hover tool hover = HoverTool(tooltips = [ ('State','@state'),('brew','@year'+" bbls")], toggleable=False) #Create color bar. color_bar = ColorBar(color_mapper=color_mapper, label_standoff=10,width = 590, height = 20, border_line_color=None,location = (0,0), orientation = 'horizontal', major_label_overrides = tick_labels) #Create figure object. plot = figure(plot_width=640, plot_height=420, aspect_scale=0.85, title = 'State Craft Beer Sales 2018') plot.add_tools(hover) plot.xgrid.grid_line_color = None plot.ygrid.grid_line_color = None plot.background_fill_color = "#F5F5F5" plot.axis.visible = False initial_map = Patches(xs='xs',ys='ys', fill_color = {'field' : 'year', 'transform' : color_mapper}, line_color = 'white', line_width = 0.15, fill_alpha = 0.5) selected_state = Patches(line_width = 1, fill_color= {'field' : 'year', 'transform' : color_mapper}, line_color='#00022b', fill_alpha = 0.5) nonselected_state = Patches(line_width = 0.15, fill_color = {'field' : 'year', 'transform' : color_mapper}, line_color='white', fill_alpha = 0.5) plot.add_glyph(geosource, initial_map, selection_glyph = selected_state, nonselection_glyph = nonselected_state) #Specify figure layout. plot.add_tools(TapTool()) plot.on_event(Tap, callback) plot.add_layout(color_bar, 'below') splot = figure(plot_width=320, plot_height=300, match_aspect=True, title=None, toolbar_location=None) tplot = figure(plot_width=320, plot_height=300, title=None, toolbar_location=None, tools='') sales_plot = figure(plot_width=320, plot_height=300, title="Sales 2008-2018", x_axis_label = 'Year', y_axis_label = 'Barrels of Craft Beer Produced (x 100 000)', toolbar_location=None) numco_plot = figure(plot_width=320, plot_height=300, title="Number of Companies 2008-2018", x_axis_label = 'Year', y_axis_label = 'Number of craft beer breweries', toolbar_location=None)
def getCountyPlot(): init_sources = getCountySources() str_sources = {} dictionary_of_sources = {} for year in init_sources.keys(): try: str_sources['_' + str(year)] = assignCountyColors( init_sources[year][year]) except: str_sources['_' + str(year)] = assignCountyColors( init_sources[year], valid=False) dictionary_of_sources[year] = '_' + str(year) jssources = str(dictionary_of_sources).replace("'", "") renderer_source = str_sources['_2006'] hover = HoverTool(tooltips=[ ("County", "@names"), ("Damages", "@damages"), ]) p = figure(title="Damage Done", toolbar_location="left", tools=[hover], plot_width=900, plot_height=500) p.xgrid.visible = False p.ygrid.visible = False p.xaxis.visible = False p.yaxis.visible = False county_glyph = Patches(xs='x', ys='y', fill_alpha=0.5, fill_color='color', line_color="#884444", line_width=1, line_alpha=1) jscode = """var year = slider.get('value'), sources = %s, new_source_data = sources[year].get('data'); renderer_source.set('data', new_source_data); """ % jssources callback = CustomJS(args=str_sources, code=jscode) slider = Slider(start=2005, end=2017, step=1, value=2006, title='Year', callback=callback) callback.args["renderer_source"] = renderer_source callback.args["slider"] = slider text_x = -115 text_y = 45 funds = [ '< 100 K', '< 1 M', '< 5 M', '< 10 M', '< 50 M', '< 100 M', '< 500 M', '> 500 M' ][::-1] colored = list(range(8)) p.add_glyph( Text(x=text_x - 2, y=text_y + 2, text=['Amount of Funds Raised'], text_font_size='10pt', text_color='#666666', text_align='left')) for i, fund in enumerate(funds): p.add_glyph( Text(x=text_x + 1, y=text_y, text=[fund], text_font_size='10pt', text_color='#666666', text_align='left')) p.add_glyph( Circle(x=text_x, y=text_y + 0.4, fill_color=OrRd9[colored[i]], size=15, line_color=None, fill_alpha=0.8)) text_y = text_y - 2 p.add_glyph(renderer_source, county_glyph) return slider, p
def htmlclassifiedplot(df, prediction): p, p2, p3 = lineplots(df) a = prediction b = list(a[0:-1]) dd = list(np.array(df['DEPT'])) ddd = [] c = [] #averaging sam = 67 for i in range(round(len(a) / sam)): bb = b[i * sam:(i * sam + sam)] c.append(list(stats.mode(bb)[0])[0]) ddd.append(dd[i * sam]) d2 = [round(d, 2) for d in ddd] values = c[0:-1] depths = d2 #lithologies lithologies = [ "sand", "shale", "siltstone", "Interbededd sand-shale", "limestone", "mudstone", "volcanic", "dolomite" ] thicks = [abs(depths[i + 1] - depths[i]) for i in range((len(values)))] #initiation of variables y1 = [] y2 = [] y3 = [] y4 = [] y5 = [] y6 = [] y7 = [] y8 = [] x1 = [] x2 = [] x3 = [] x4 = [] x5 = [] x6 = [] x7 = [] x8 = [] th = [] th2 = [] th3 = [] th4 = [] th5 = [] th6 = [] th7 = [] th8 = [] lit = [] lit2 = [] lit3 = [] lit4 = [] lit5 = [] lit6 = [] lit7 = [] lit8 = [] #classes for i in range((len(values))): if values[i] == 1: yy = depths[i] xx = 0 * i ttt = thicks[i] th.append(ttt) x1.append(xx) y1.append(yy) l = lithologies[0] lit.append(l) for i in range((len(values))): if values[i] == 2: yy = depths[i] xx = 0 * i ttt = thicks[i] th2.append(ttt) x2.append(xx) y2.append(yy) l = lithologies[1] lit2.append(l) for i in range((len(values))): if values[i] == 3: yy = depths[i] xx = 0 * i x3.append(xx) y3.append(yy) ttt = thicks[i] th3.append(ttt) l = lithologies[2] lit3.append(l) for i in range((len(values))): if values[i] == 4: yy = depths[i] xx = 0 * i x4.append(xx) y4.append(yy) ttt = thicks[i] th4.append(ttt) l = lithologies[3] lit4.append(l) for i in range((len(values))): if values[i] == 5: yy = depths[i] xx = 0 * i x5.append(xx) y5.append(yy) ttt = thicks[i] th5.append(ttt) l = lithologies[4] lit5.append(l) for i in range((len(values))): if values[i] == 6: yy = depths[i] xx = 0 * i x6.append(xx) y6.append(yy) ttt = thicks[i] th6.append(ttt) l = lithologies[5] lit6.append(l) for i in range((len(values))): if values[i] == 7: yy = depths[i] xx = 0 * i x7.append(xx) y7.append(yy) ttt = thicks[i] th7.append(ttt) l = lithologies[6] lit7.append(l) for i in range((len(values))): if values[i] == 8: yy = depths[i] xx = 0 * i x8.append(xx) y8.append(yy) ttt = thicks[i] th8.append(ttt) l = lithologies[7] lit8.append(l) # shape of the rectangle xpts = np.array([1, -1, -1, 1]) ypts = np.array([0, 0, 1, 1]) # coordinates of all rectangles source3 = ColumnDataSource( dict(xs=[xpts + xx for i, xx in enumerate(x3)], ys=[ypts * m + yy for m, yy in zip(th3, y3)], lith=[1 * ll for ll in lit3])) source1 = ColumnDataSource( dict(xs=[xpts + xx for i, xx in enumerate(x1)], ys=[ypts * m + yy for m, yy in zip(th, y1)], lith=[1 * ll for ll in lit])) source2 = ColumnDataSource( dict(xs=[xpts + xx for i, xx in enumerate(x2)], ys=[ypts * m + yy for m, yy in zip(th2, y2)], lith=[1 * ll for ll in lit2])) source4 = ColumnDataSource( dict(xs=[xpts + xx for i, xx in enumerate(x4)], ys=[ypts * m + yy for m, yy in zip(th4, y4)], lith=[1 * ll for ll in lit4])) source5 = ColumnDataSource( dict(xs=[xpts + xx for i, xx in enumerate(x5)], ys=[ypts * m + yy for m, yy in zip(th5, y5)], lith=[1 * ll for ll in lit5])) source6 = ColumnDataSource( dict(xs=[xpts + xx for i, xx in enumerate(x6)], ys=[ypts * m + yy for m, yy in zip(th6, y6)], lith=[1 * ll for ll in lit6])) source7 = ColumnDataSource( dict(xs=[xpts + xx for i, xx in enumerate(x7)], ys=[ypts * m + yy for m, yy in zip(th7, y7)], lith=[1 * ll for ll in lit7])) source8 = ColumnDataSource( dict(xs=[xpts + xx for i, xx in enumerate(x8)], ys=[ypts * m + yy for m, yy in zip(th8, y8)], lith=[1 * ll for ll in lit8])) # parameters of the figure plot = figure(title="Lithologies", x_axis_label='', y_axis_label='depth (m)', x_range=(-1, 1), plot_width=300, plot_height=800, y_range=p.y_range, h_symmetry=False, v_symmetry=False, tools="pan,ywheel_zoom,lasso_select,box_zoom,hover,reset", tooltips=[("Lithology", "@lith")]) #min_border=0, #plot.xaxis.visible = False glyph = Patches(xs="xs", ys="ys", fill_color="#F4D03F", line_color='blue', line_alpha=0) glyph2 = Patches(xs="xs", ys="ys", fill_color="#6E2C00", line_color='blue', line_alpha=0) glyph3 = Patches(xs="xs", ys="ys", fill_color="#DC7633", line_color='blue', line_alpha=0) glyph4 = Patches(xs="xs", ys="ys", fill_color="#F5B041", line_color='blue', line_alpha=0) glyph5 = Patches(xs="xs", ys="ys", fill_color="#AED6F1", line_color='blue', line_alpha=0) glyph6 = Patches(xs="xs", ys="ys", fill_color="#1B4F72", line_color='blue', line_alpha=0) glyph7 = Patches(xs="xs", ys="ys", fill_color="#196F3D", line_color='blue', line_alpha=0) glyph8 = Patches(xs="xs", ys="ys", fill_color="#A569BD", line_color='blue', line_alpha=0) #glyph9 = Patches(xs="xs", ys="ys", fill_color="#C41286", line_color='blue', line_alpha=0) plot.add_glyph(source3, glyph3) plot.add_glyph(source1, glyph) plot.add_glyph(source2, glyph2) plot.add_glyph(source4, glyph4) plot.add_glyph(source5, glyph5) plot.add_glyph(source6, glyph6) plot.add_glyph(source7, glyph7) plot.add_glyph(source8, glyph8) #plot.add_glyph(source9, glyph9) sss = gridplot([[p, p2, p3, plot]], sizing_mode="scale_width") return file_html(sss, CDN, "my plot")
def modify_doc(doc): def callback(event): selected = geosource.selected.indices yr = slider.value data = get_json(str(yr), selected[0]) sgeosource.geojson = data[0] text_year.text = str(yr) text_state.text = data[1] text_beer.text = str(f"{data[2]:,d}") text_numco.text = str(numco(data[1], str(yr))) text_rank.text = str(rank(data[1], str(yr))) text_rate.text = str(rate(data[1], str(yr))) + '%' text_adults.text = str(adults(data[1])) + '%' text_capita.text = str(capita(data[1], str(yr))) company_selection.labels = company(data[1]) initial_companies = [ company_selection.labels[i] for i in company_selection.active ] src.data = make_dataset(initial_companies).data coordinates = xysource(data[1], df1) ycoordinate = [i / 100000 for i in coordinates[1]] statesource.data = dict(x=coordinates[0], y=ycoordinate) coordinatesplot = xysource(data[1], df4) numcosource.data = dict(x=coordinatesplot[0], y=coordinatesplot[1]) splot.visible = True tplot.visible = True def xysource(state, df5): df2 = df5.loc[df5['states'] == state] df2 = df2.drop('states', 1) list_x = [int(i) for i in list(df2)] list_y = df2.values[0] return [list_x, list_y] flask_args = doc.session_context.request.arguments try: plot_title = flask_args.get('plot_title')[0].decode("utf-8") except: plot_title = "Sea Surface Temperature at 43.18, -70.43" try: dataset = flask_args.get('dataset')[0].decode("utf-8") except: dataset = "Dataset One" try: unit_type = flask_args.get('unit_type')[0].decode("utf-8") except: unit_type = "Celcius" try: theme = flask_args.get('theme')[0].decode("utf-8") except: theme = "default" gdf = gpd.GeoDataFrame.from_file( join(dirname(__file__), 'data/states', 'gz_2010_us_040_00_20m.shp'))[[ 'NAME', 'geometry', 'GEO_ID', 'CENSUSAREA' ]] yr = 2018 gdf.columns = ['state', 'geometry', 'geo_id', 'censusarea'] gdf = gdf.drop(gdf.index[26]) gdf = gdf.drop(gdf.index[7]) df_company = pd.DataFrame(get_data(query_craft), columns=[ 'company', 'state', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018' ]) df_companies = df_company.replace({"state": states}) df_companies = df_companies.astype({ "2008": int, "2009": int, "2010": int, "2011": int, "2012": int, "2013": int, "2014": int, "2015": int, "2016": int, "2017": int, "2018": int }) df = pd.DataFrame(dframe(query_state), columns=['states', '2008', '2009', '2010']) df1 = df.replace({"states": states}) df1 = df1.astype({"2008": int, "2009": int, "2010": int}) df_brew = pd.DataFrame(get_data(query_brew), columns=[ 'state', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018' ]) df_brew = df_brew.astype({ "2011": int, "2012": int, "2013": int, "2014": int, "2015": int, "2016": int, "2017": int, "2018": int }) df1 = df1.merge(df_brew, left_on='states', right_on='state') df1 = df1.drop('state', 1) df3 = pd.DataFrame(dframe(query_num_co), columns=[ 'states', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017' ]) df4 = df3.replace({"states": states}) df4 = df4.astype({ "2008": int, "2009": int, "2010": int, "2011": int, "2012": int, "2013": int, "2014": int, "2015": int, "2016": int, "2017": int }) df_numco = pd.DataFrame(get_data(query_numco), columns=['state', '2018']) df_numco = df_numco.astype({"2018": int}) df4 = df4.merge(df_numco, left_on='states', right_on='state') df4 = df4.drop('state', 1) df_pop = pd.DataFrame(get_data(query_population), columns=['state', 'population', 'percent', 'adults']) df_pop = df_pop.astype({"percent": float, "adults": int}) df_pop['percent'] = df_pop['percent'] * 100 def numco(state, year): merged = df4.loc[df4['states'] == state] numco_text = merged.iloc[0][year] return numco_text def rank(state, year): df_rank = df4[['states', year]] df = df_rank.sort_values(year, ascending=False) df = df.reset_index(drop=True) idx = df.index[df['states'] == state] idx = idx[0] + 1 return idx def rate(state, year): rate = (100 * df4.loc[df4['states'] == state][year].values[0] ) / df4[year].sum() return rate.round(2) def adults(state): adults = df_pop.loc[df_pop['state'] == state]['percent'].values[0] return adults.round(2) def capita(state, year): adults = df_pop.loc[df_pop['state'] == state]['adults'].values[0] num = numco(state, year) kf = 100000 capita = (num / adults) * kf print(capita) return capita.round(1) def get_json(year, idx): df_yr = df1[['states', year]] df_yr.columns = ['states', 'year'] merged = gdf.merge(df_yr, left_on='state', right_on='states') state_text = '' beer_text = '' if idx is not None: merged = merged.iloc[[idx]] state_text = merged.iloc[0]['state'] beer_text = merged.iloc[0]['year'] merged_json = json.loads(merged.to_json()) json_data = json.dumps(merged_json) return [json_data, state_text, beer_text] #Input GeoJSON source that contains features for plotting. geosource = GeoJSONDataSource(geojson=get_json('2018', None)[0]) #Define a sequential multi-hue color palette. palette = ['#084594', '#2171b5', '#4292c6', '#6baed6', '#9ecae1'] #palette = d3['Category20b'][4] #Reverse color order so that dark blue is highest obesity. palette = palette[::-1] #Instantiate LinearColorMapper that linearly maps numbers in a range, into a sequence of colors. color_mapper = LinearColorMapper(palette=palette, low=0, high=2500000, nan_color='#d9d9d9') #Define custom tick labels for color bar. tick_labels = { '0': '0%', '5': '5%', '10': '10%', '15': '15%', '20': '20%', '25': '25%', '30': '30%', '35': '35%', '40': '>40%' } #Add hover tool hover = HoverTool(tooltips=[('State', '@state'), ('brew', '@year' + " bbls")], toggleable=False) #Create color bar. color_bar = ColorBar(color_mapper=color_mapper, label_standoff=10, width=590, height=20, border_line_color=None, location=(0, 0), orientation='horizontal', major_label_overrides=tick_labels) #Create figure object. plot = figure(plot_width=640, plot_height=420, aspect_scale=0.85, title='State Craft Beer Sales 2018') plot.add_tools(hover) plot.xgrid.grid_line_color = None plot.ygrid.grid_line_color = None plot.background_fill_color = "#F5F5F5" #Add patch renderer to figure. plot.axis.visible = False initial_map = Patches(xs='xs', ys='ys', fill_color={ 'field': 'year', 'transform': color_mapper }, line_color='white', line_width=0.15, fill_alpha=0.5) selected_state = Patches(line_width=1, fill_color={ 'field': 'year', 'transform': color_mapper }, line_color='#00022b', fill_alpha=0.5) nonselected_state = Patches(line_width=0.15, fill_color={ 'field': 'year', 'transform': color_mapper }, line_color='white', fill_alpha=0.5) plot.add_glyph(geosource, initial_map, selection_glyph=selected_state, nonselection_glyph=nonselected_state) #Specify figure layout. plot.add_tools(TapTool()) plot.on_event(Tap, callback) plot.add_layout(color_bar, 'below') splot = figure(plot_width=320, plot_height=300, match_aspect=True, title=None, toolbar_location=None) tplot = figure(plot_width=320, plot_height=300, title=None, toolbar_location=None, tools='') sales_plot = figure( plot_width=320, plot_height=300, title="Sales 2008-2018", x_axis_label='Year', y_axis_label='Barrels of Craft Beer Produced (x 100 000)', toolbar_location=None) numco_plot = figure(plot_width=320, plot_height=300, title="Number of Companies 2008-2018", x_axis_label='Year', y_axis_label='Number of craft beer breweries', toolbar_location=None) splot.axis.visible = False tplot.axis.visible = False splot.grid.visible = False tplot.grid.visible = False splot.outline_line_width = 0 tplot.outline_line_width = 0 # splot.visible = False # tplot.visible = False sgeosource = GeoJSONDataSource(geojson=get_json('2018', 2)[0]) splot.patches('xs', 'ys', source=sgeosource, fill_color='#131E3A', line_color='black', line_width=0.25, fill_alpha=1) year_source = ColumnDataSource({'year': ['2018']}) text_year = Label(x=250, y=250, x_units='screen', y_units='screen', text='2018', text_color='#131E3A', text_font_size='16pt', text_font_style='bold') text_state = Label(x=0, y=250, x_units='screen', y_units='screen', text='California', text_color='#131E3A', text_font_size='16pt', text_font_style='bold') text_beer = Label(x=145, y=220, x_units='screen', y_units='screen', text='1,032,369', text_color='#013240', text_font_size='28pt', text_font_style='bold', text_font='Roboto', text_baseline='middle', text_align='right', x_offset=25) text_val1 = Label(x=175, y=222, x_units='screen', y_units='screen', text='Barrels of Craft Beer', text_color='#013220', text_font_size='11pt', text_font_style='normal', text_font='Roboto') text_val2 = Label(x=175, y=208, x_units='screen', y_units='screen', text='Produced per Year', text_color='#013220', text_font_size='11pt', text_font_style='normal', text_font='Roboto') text_numco = Label(x=145, y=180, x_units='screen', y_units='screen', text='750', text_color='#013240', text_font_size='28pt', text_font_style='bold', text_font='Roboto', text_baseline='middle', text_align='right', x_offset=25) text_val3 = Label(x=175, y=182, x_units='screen', y_units='screen', text='Craft Breweries', text_color='#013220', text_font_size='11pt', text_font_style='normal', text_font='Roboto') text_val4 = Label(x=175, y=168, x_units='screen', y_units='screen', text='Operating per Year', text_color='#013220', text_font_size='11pt', text_font_style='normal', text_font='Roboto') text_rank = Label(x=145, y=140, x_units='screen', y_units='screen', text='1', text_color='#013240', text_font_size='28pt', text_font_style='bold', text_font='Roboto', text_baseline='middle', text_align='right', x_offset=25) text_val5 = Label(x=175, y=142, x_units='screen', y_units='screen', text='Most Craft', text_color='#013220', text_font_size='11pt', text_font_style='normal', text_font='Roboto') text_val6 = Label(x=175, y=128, x_units='screen', y_units='screen', text='Breweries in the US', text_color='#013220', text_font_size='11pt', text_font_style='normal', text_font='Roboto') text_rate = Label(x=145, y=100, x_units='screen', y_units='screen', text='5%', text_color='#013240', text_font_size='28pt', text_font_style='bold', text_font='Roboto', text_baseline='middle', text_align='right', x_offset=25) text_val7 = Label(x=175, y=102, x_units='screen', y_units='screen', text='of US Craft Breweries', text_color='#013220', text_font_size='11pt', text_font_style='normal', text_font='Roboto') text_val8 = Label(x=175, y=88, x_units='screen', y_units='screen', text='', text_color='#013220', text_font_size='11pt', text_font_style='normal', text_font='Roboto') text_adults = Label(x=145, y=60, x_units='screen', y_units='screen', text='75%', text_color='#013240', text_font_size='28pt', text_font_style='bold', text_font='Roboto', text_baseline='middle', text_align='right', x_offset=25) text_val9 = Label(x=175, y=62, x_units='screen', y_units='screen', text='21+ Adults in state', text_color='#013220', text_font_size='11pt', text_font_style='normal', text_font='Roboto') text_val10 = Label(x=175, y=48, x_units='screen', y_units='screen', text='', text_color='#013220', text_font_size='11pt', text_font_style='normal', text_font='Roboto') text_capita = Label(x=145, y=20, x_units='screen', y_units='screen', text='2.8%', text_color='#013240', text_font_size='28pt', text_font_style='bold', text_font='Roboto', text_baseline='middle', text_align='right', x_offset=25) text_val11 = Label(x=175, y=22, x_units='screen', y_units='screen', text='Breweries per', text_color='#013220', text_font_size='11pt', text_font_style='normal', text_font='Roboto') text_val12 = Label(x=175, y=8, x_units='screen', y_units='screen', text='100,000 21+ Adults', text_color='#013220', text_font_size='11pt', text_font_style='normal', text_font='Roboto') coordinates = xysource('California', df1) ycoordinate = [i / 100000 for i in coordinates[1]] statesource = ColumnDataSource(dict(x=coordinates[0], y=ycoordinate)) coordinatesplot = xysource('California', df4) numcosource = ColumnDataSource( dict(x=coordinatesplot[0], y=coordinatesplot[1])) sales_plot.line('x', 'y', source=statesource, line_width=3, line_alpha=0.6) numco_plot.line('x', 'y', source=numcosource, line_width=3, line_alpha=0.6) tplot.add_layout(text_year) tplot.add_layout(text_state) tplot.add_layout(text_beer) tplot.add_layout(text_val1) tplot.add_layout(text_val2) tplot.add_layout(text_numco) tplot.add_layout(text_val3) tplot.add_layout(text_val4) tplot.add_layout(text_rank) tplot.add_layout(text_val5) tplot.add_layout(text_val6) tplot.add_layout(text_rate) tplot.add_layout(text_val7) tplot.add_layout(text_val8) tplot.add_layout(text_adults) tplot.add_layout(text_val9) tplot.add_layout(text_val10) tplot.add_layout(text_capita) tplot.add_layout(text_val11) tplot.add_layout(text_val12) # glyph = Text(x="x", y="y", text="text", angle=0.3, text_color="#96deb3") # tplot.add_glyph(source, glyph) def update_plot(attr, old, new): yr = slider.value new_data = get_json(str(yr), None)[0] geosource.geojson = new_data plot.title.text = 'State Craft Beer Sales, %d' % yr # Make a slider object: slider slider = Slider(title='Year', start=2008, end=2018, step=1, value=2018) slider.on_change('value', update_plot) def make_dataset(company_list): xs = [] ys = [] colors = [] labels = [] # src_circle = [] for i, company in enumerate(company_list): df_co = df_companies.loc[df_companies['company'] == company] df_co = df_co.drop(['company', 'state'], axis=1) list_x = [int(i) for i in list(df_co)] list_y = df_co.values[0] xs.append(list_x) ys.append(list_y) colors.append(company_colors[i]) labels.append(company) new_src = ColumnDataSource(data={ 'x': xs, 'y': ys, 'color': colors, 'label': labels }) # for i in range(0, len(new_src.data['x'])): # print (i) # src_circle.append(ColumnDataSource(data={'x': new_src.data['x'][i], 'y': new_src.data['y'][i]})) return new_src def make_plot(src): p = figure(plot_width=800, plot_height=420, title='Craft Beer Sales by State Companies 2008-2018', x_axis_label='Year', y_axis_label='Barrels of Craft Beer Produced, bbls') p.multi_line('x', 'y', color='color', line_alpha=0.6, hover_line_alpha=1.0, legend='label', line_width=3, name='needshover', source=src) # for i in src_circle: # p.circle('x', 'y', fill_color="white", color = 'grey', size=8, source = i) hover = HoverTool(names=['needshover'], tooltips=[('Company', '@label'), ('Year', '$x{int}'), ('Barrels', '$data_y' + " bbls")]) p.add_tools(hover) p.yaxis.formatter = NumeralTickFormatter(format="0.0 a") p.legend.location = "top_left" return p def update(attr, old, new): companies_to_plot = [ company_selection.labels[i] for i in company_selection.active ] new_src = make_dataset(companies_to_plot) src.data.update(new_src.data) def company(state): available_companies = df_companies.loc[df_companies['state'] == state][:] sort_companies = list(set(available_companies['company'][:20])) sort_companies.sort() return sort_companies company_selection = CheckboxGroup(labels=company('California'), active=[0, 1]) company_selection.on_change('active', update) initial_companies = [ company_selection.labels[i] for i in company_selection.active ] company_colors = Category20_16 company_colors.sort() src = make_dataset(initial_companies) # src_circle = make_dataset(initial_companies)[1] plot_state = make_plot(src) controls = WidgetBox(company_selection, width=200) l1 = row(controls, plot_state) if plot_title == '1': r = row([plot, tplot], sizing_mode='stretch_height') doc.add_root(column(r, l1)) else: l = layout([[plot], [splot, tplot], [numco_plot, sales_plot]]) doc.add_root(column(slider, l)) doc.theme = Theme(filename=f"theme-{theme}.yaml")
def helper(obs: Observable, plot=None): # Domain-specific rendering if isinstance(obs, GraphObservable): if plot is None: plot = figure(x_range=self.x_rng, y_range=self.y_rng, tooltips=[], width=self.plot_width, height=self.plot_height) plot.axis.visible = False plot.xgrid.grid_line_color = None plot.ygrid.grid_line_color = None renderer = from_networkx(G, layout) plot.renderers.append(renderer) plot.toolbar_location = None if obs.Gd is GraphDomain.nodes: plot.add_tools(HoverTool(tooltips=[('value', '@value'), ('node', '@node')])) plot.renderers[0].node_renderer.data_source.data['node'] = list(map(str, items[0].G.nodes())) plot.renderers[0].node_renderer.data_source.data['value'] = obs.y cmap = LinearColorMapper(palette=self.node_palette, low=self.node_rng[0], high=self.node_rng[1]) self.node_cmaps[obs.plot_id] = cmap if isinstance(obs, gds): plot.renderers[0].node_renderer.data_source.data['thickness'] = [3 if (x in obs.X_dirichlet or x in obs.X_neumann) else 1 for x in obs.X] plot.renderers[0].node_renderer.glyph = Ellipse(height=self.node_size, width=self.node_size, fill_color=field('value', cmap), line_width='thickness') else: plot.renderers[0].node_renderer.glyph = Ellipse(height=self.node_size, width=self.node_size, fill_color=field('value', cmap)) if self.colorbars: cbar = ColorBar(color_mapper=cmap, ticker=BasicTicker(), title='node') cbar.major_label_text_font_size = "15pt" plot.add_layout(cbar, 'right') elif obs.Gd is GraphDomain.edges: plot.add_tools(HoverTool(tooltips=[('value', '@value'), ('edge', '@edge')])) self.prep_layout_data(obs, G, layout) obs.arr_source.data['edge'] = list(map(str, items[0].G.edges())) self.draw_arrows(obs, obs.y) plot.renderers[0].edge_renderer.data_source.data['value'] = obs.arr_source.data['value'] cmap = LinearColorMapper(palette=self.edge_palette, low=self.edge_rng[0], high=self.edge_rng[1]) self.edge_cmaps[obs.plot_id] = cmap arrows = Patches(xs='xs', ys='ys', fill_color=field('value', cmap)) plot.add_glyph(obs.arr_source, arrows) if self.colorbars: cbar = ColorBar(color_mapper=cmap, ticker=BasicTicker(), title='edge') cbar.major_label_text_font_size = "15pt" plot.add_layout(cbar, 'right') if self.edge_colors: plot.renderers[0].edge_renderer.glyph = MultiLine(line_width=5, line_color=field('value', cmap)) elif isinstance(obs, gds): plot.renderers[0].edge_renderer.data_source.data['thickness'] = [3 if (x in obs.X_dirichlet or x in obs.X_neumann) else 1 for x in obs.X] plot.renderers[0].edge_renderer.glyph = MultiLine(line_width='thickness') elif obs.Gd is GraphDomain.faces: plot.add_tools(HoverTool(tooltips=[('value', '@value'), ('face', '@face')])) cmap = LinearColorMapper(palette=self.face_palette, low=self.face_rng[0], high=self.face_rng[1]) self.face_cmaps[obs.plot_id] = cmap obs.face_source = ColumnDataSource() xs = [[orig_layout[n][0] for n in f] for f in obs.faces] ys = [[orig_layout[n][1] for n in f] for f in obs.faces] if hasattr(obs.G, 'rendered_faces'): # Hacky xs = [xs[i] for i in obs.G.rendered_faces] ys = [ys[i] for i in obs.G.rendered_faces] obs.face_source.data['xs'] = xs obs.face_source.data['ys'] = ys obs.face_source.data['value'] = np.zeros(len(xs)) faces = Patches(xs='xs', ys='ys', fill_color=field('value', cmap), line_color='#FFFFFF', line_width=2) plot.add_glyph(obs.face_source, faces) if self.face_orientations: # TODO: only works for convex faces obs.centroid_x, obs.centroid_y = np.array([np.mean(row) for row in xs]), np.array([np.mean(row) for row in ys]) obs.radius = 0.3 * np.array([min([np.sqrt((xs[i][j] - obs.centroid_x[i])**2 + (ys[i][j] - obs.centroid_y[i])**2) for j in range(len(xs[i]))]) for i in range(len(xs))]) height = 2/5 * obs.radius arrows_ys = np.stack((obs.centroid_y-obs.radius, obs.centroid_y-obs.radius+height/2, obs.centroid_y-obs.radius-height/2), axis=1) obs.face_source.data['centroid_x'] = obs.centroid_x obs.face_source.data['centroid_y'] = obs.centroid_y obs.face_source.data['radius'] = obs.radius obs.face_source.data['arrows_ys'] = (arrows_ys + 0.01).tolist() self.draw_face_orientations(obs, cmap) arcs = Arc(x='centroid_x', y='centroid_y', radius='radius', start_angle=-0.9, end_angle=4.1, line_color=field('arrow_color', cmap)) arrows = Patches(xs='arrows_xs', ys='arrows_ys', fill_color=field('arrow_color', cmap), line_color=field('arrow_color', cmap)) plot.add_glyph(obs.face_source, arcs) plot.add_glyph(obs.face_source, arrows) if self.colorbars: cbar = ColorBar(color_mapper=cmap, ticker=BasicTicker(), title='face') cbar.major_label_text_font_size = "15pt" plot.add_layout(cbar, 'right') else: raise Exception('unknown graph domain.') elif isinstance(obs, PointObservable): plot = figure(width=self.plot_width, height=self.plot_height) plot.add_tools(HoverTool(tooltips=[('time', '@t'), ('value', '@value')])) plot.toolbar_location = None plot.x_range.follow = 'end' plot.x_range.follow_interval = 10.0 plot.x_range.range_padding = 0 plot.xaxis.major_label_text_font_size = "15pt" plot.xaxis.axis_label = 'Time' plot.yaxis.major_label_text_font_size = "15pt" plot.y_range.range_padding_units = 'absolute' plot.y_range.range_padding = obs.render_params['min_res'] / 2 obs.src = ColumnDataSource({'t': [], 'value': []}) glyph = Line(x='t', y='value') plot.add_glyph(obs.src, glyph) # plot.line('t', 'value', line_color='black', source=obs.src) elif isinstance(obs, VectorObservable): plot = figure(width=self.plot_width, height=self.plot_height, y_range=obs.domain) plot.add_tools(HoverTool(tooltips=[('time', '@t'), ('value', '@val'), ('y', '@y')])) plot.toolbar_location = None plot.x_range.follow = 'end' plot.x_range.follow_interval = 10.0 plot.x_range.range_padding = 0 # plot.xaxis.major_label_text_font_size = "15pt" # plot.xaxis.axis_label = 'Time' # plot.yaxis.major_label_text_font_size = "15pt" obs.src = ColumnDataSource({'t': [], 'y': [], 'w': [], 'val': []}) obs.cmap = LinearColorMapper(palette=self.vec_palette, low=0, high=1) obs.last_t = obs.t plot.rect(x='t', y='y', width='w', height=1, source=obs.src, line_color=None, fill_color=field('val', obs.cmap)) if self.colorbars: cbar = ColorBar(color_mapper=obs.cmap, ticker=BasicTicker(), title='value') cbar.major_label_text_font_size = "15pt" plot.add_layout(cbar, 'right') else: raise Exception('unknown observable type: ', obs) return plot
def bkExport(self, settings): #layer = iface.legendInterface().layers()[0] layer = settings["layer"] field = settings["field"] gdfList = [] total = float(layer.featureCount()) counter = 0 for feature in layer.getFeatures(): counter = counter + 1 self.dlg.progressBar.setValue(counter / total * 100) featJsonString = feature.geometry().geometry().asJSON(17) featJson = json.loads(featJsonString) df = {} df["geometry"] = shape(featJson) if field: df["data"] = feature[field] else: df["data"] = 0 df["class"] = -1 for hField in settings["hoverFields"]: df[hField[0]] = feature[hField[0]] gdf = gpd.GeoDataFrame([df]) gdfList.append(gdf) gdf2 = gpd.GeoDataFrame(pd.concat(gdfList, ignore_index=True)) lons, lats = self.gpd_bokeh(gdf2) data = list(gdf2["data"]) height = settings["height"] width = settings["width"] renderer = layer.rendererV2() if renderer.type() == 'singleSymbol': print "singleSymbol" color = renderer.symbol().color().name() color_mapper = CategoricalColorMapper(factors=[-1], palette=[color]) elif renderer.type() == 'categorizedSymbol': print "categorizedSymbol" categories = renderer.categories() for i in xrange(len(categories)): if categories[i].value(): try: gdf2["class"][( gdf2["data"] == categories[i].value())] = i except: gdf2["class"][(gdf2["data"] == float( categories[i].value()))] = i colorPalette = [ symbol.color().name() for symbol in renderer.symbols() ] color_mapper = CategoricalColorMapper(factors=sorted( list(gdf2["class"].unique())), palette=colorPalette) elif renderer.type() == 'graduatedSymbol': print "graduatedSymbol" ranges = renderer.ranges() gdf2["class"] = map(renderer.legendKeyForValue, gdf2["data"]) colorPalette = [ symbol.color().name() for symbol in renderer.symbols() ] color_mapper = CategoricalColorMapper(factors=sorted( list(gdf2["class"].unique())), palette=colorPalette) else: print "otherSymbols" if settings["toolbar_location"] == "none": TOOLS = "" else: TOOLS = "pan,wheel_zoom,box_zoom,reset,hover,save" colorClass = list(gdf2["class"]) source = ColumnDataSource( data=dict(x=lons, y=lats, data=data, category=colorClass)) for hField in settings["hoverFields"]: source.add(gdf2[hField[0]], name=hField[0]) if settings["GoogleEnabled"]: print("Enable Google") map_options = GMapOptions( lat=np.nanmean([val for sublist in lats for val in sublist]), lng=np.nanmean([val for sublist in lons for val in sublist]), map_type=settings["googleMapType"], zoom=settings["zoomLevel"]) plot = GMapPlot(plot_width=width, plot_height=height, x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, api_key=settings["GMAPIKey"]) source_patches = source patches = Patches(xs='x', ys='y', fill_alpha=settings["alpha"] / 100.0, line_color=settings["outlineColor"], line_width=settings["outlineWidth"], fill_color={ 'field': 'category', 'transform': color_mapper }) patches_glyph = plot.add_glyph(source_patches, patches) plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool(), HoverTool()) else: #plot_width=width, plot_height=height, plot = figure(title=settings["title"], tools=TOOLS, plot_width=width, plot_height=height, x_axis_location=None, y_axis_location=None) plot.grid.grid_line_color = None plot.patches('x', 'y', source=source, fill_alpha=settings["alpha"] / 100.0, line_color=settings["outlineColor"], line_width=settings["outlineWidth"], fill_color={ 'field': 'category', 'transform': color_mapper }) plot.border_fill_color = settings["border_fill_color"] plot.background_fill_color = settings["background_fill_color"] plot.background_fill_alpha = settings["background_fill_alpha"] plot.outline_line_alpha = settings["outline_line_alpha"] plot.outline_line_color = settings["outline_line_color"] plot.outline_line_width = settings["outline_line_width"] if settings["toolbar_location"] == "none": plot.toolbar_location = None else: plot.toolbar_location = settings["toolbar_location"] plot.min_border_left = settings["min_border_left"] plot.min_border_right = settings["min_border_right"] plot.min_border_top = settings["min_border_top"] plot.min_border_bottom = settings["min_border_bottom"] plot.sizing_mode = settings["sizing_mode"] if settings["hoverFields"]: hover = plot.select_one(HoverTool) hover.point_policy = "follow_mouse" hover.tooltips = [ #(field, "@data") #("(Long, Lat)", "($x, $y)"), ] for hField in settings["hoverFields"]: temp = "@" + hField[0] hover.tooltips.append((hField[1], temp)) if settings["BokehJS"] == "CDN": print("CDN") html = file_html(plot, CDN, "my plot") elif settings["BokehJS"] == "INLINE": print("INLINE") html = file_html(plot, INLINE, "my plot") with open(self.settings["outputFile"] + "/map.html", "w") as my_html: my_html.write(html) settings["layer"] = settings["layer"].name() print settings with open(self.settings["outputFile"] + "/settings.json", 'w') as fp: json.dump(settings, fp)
def prepare_graph(): try: #____________ # ---- Importing & Creating base figure from Google Maps ---- #____________ knotel_off, patch_source = prepare_data() # the map is set to Manhattan map_options = GMapOptions(lat=40.741, lng=-73.995, map_type="roadmap", zoom=13, styles=json.dumps(map_other_config)) #importing GMap into a Bokeh figure p = gmap(MH_GMAPS_KEY, map_options, title="Manhattan Heatmap — A Prototype", plot_width=1070, plot_height=800, output_backend="webgl", tools=['pan', 'wheel_zoom', 'reset', 'box_select', 'tap']) #____________ # ---- OFFICES GLYPH ---- #____________ initial_office = Diamond(x="long", y="lat", size=18, fill_color="blue", fill_alpha=0.7, line_color="black", line_alpha=0.7) selected_office = Diamond(fill_color="blue", fill_alpha=1) nonselected_office = Diamond(fill_color="blue", fill_alpha=0.15, line_alpha=0.15) # glyph gets added to the plot office_renderer = p.add_glyph(knotel_off, initial_office, selection_glyph=selected_office, nonselection_glyph=nonselected_office) # hover behavior pointing to office glyph office_hover = HoverTool(renderers=[office_renderer], tooltips=[("Revenue", "@revenue{$00,}"), ("Rentable SQF", "@rentable_sqf{00,}"), ("People density", "@ppl_density"), ("Address", "@formatted_address")]) p.add_tools(office_hover) #____________ # ---- TRACT GLYPH ---- #____________ tract_renderer = p.patches(xs='xs', ys='ys', source=patch_source, fill_alpha=0, line_color='red', line_dash='dashed', hover_color='red', hover_fill_alpha=0.5) # hack to make tracts unselectable initial_tract = Patches(fill_alpha=0, line_color='red', line_dash='dashed') tract_renderer.selection_glyph = initial_tract tract_renderer.nonselection_glyph = initial_tract # hover behavior pointing to tract glyph tract_hover = HoverTool(renderers=[tract_renderer], tooltips=[("Median Household Income", "@MHI{$00,}")], mode='mouse') # p.add_tools(tract_hover) # Other figure configurations p.yaxis.axis_label = "Latitude" p.xaxis.axis_label = "Longitude" p.toolbar.active_inspect = [tract_hover, office_hover] p.toolbar.active_tap = "auto" p.toolbar.active_scroll = "auto" #____________ # ---- Adding widgets & Interactions to figure #____________ # creates a Toggle button show_office_toggle = Toggle(label='Show Leased Bldgs.', active=True, button_type='primary') # callback function for button def remove_add_office(active): office_renderer.visible = True if active else False # event handler show_office_toggle.on_click(remove_add_office) # same exact logic for tracts. To be combined into a single handler as an improvement! show_tract_toggle = Toggle(label='Show Census Tracts', active=True, button_type='danger') def remove_add_tract(active): tract_renderer.visible = True if active else False show_tract_toggle.on_click(remove_add_tract) # plotting layout = row(p, widgetbox(show_office_toggle, show_tract_toggle)) return layout except Exception as err: print("ERROR found on prepare_graph:\n{}".format(err))
def output_res(): with open(r'./twgeo_easy_rates.json', 'r') as file: json_str = file.read() geo_source = GeoJSONDataSource(geojson=json_str) twgeo_json = json.loads(json_str) pred_4week = pd.read_csv('prediction_4week.csv') areas = ['南區', '北區', '東區', '高屏區', '台北區', '中區'] models = ['CatBoost', 'XGB', 'ConvLSTM', 'GRU', 'LGBM', 'truth'] color_list = ['black', 'red', 'blue', 'green', 'cyan', 'purple'] area_dict = {} for idx, area in enumerate(areas): area_dict[area] = {} temp = pd.read_csv('./data/{}.csv'.format(area)) area_dict[area]['df'] = temp area_dict[area]['DT'] = pd.to_datetime(temp['DT'].values) area_idx = [] for i in range(22): if twgeo_json['features'][i]['properties']['area'] == area: area_idx.append(i) area_dict[area]['area_idx'] = area_idx def fig_config(fig): fig.grid.grid_line_color = None fig.toolbar.logo = None fig.toolbar_location = None fig.legend.location = "top_left" fig.legend.click_policy = "hide" fig.xaxis.axis_label = 'Date' fig.yaxis.axis_label = '腸病毒人數' future_4_weeks = [] data_dict = {} model_cds = {} pred_4week = pd.read_csv('prediction_4week.csv') pred_64week = pd.read_csv('prediction_64week.csv') pred_4week_mae = pd.read_csv('mae_4week.csv') pred_64week_mae = pd.read_csv('mae_64week.csv') for area in areas: for model in models: data_dict['{}_{}_4week'.format(area, model)] = pred_4week['{}_{}'.format( area, model)].values data_dict['{}_{}_64week'.format( area, model)] = pred_64week['{}_{}'.format(area, model)].values data_dict['{}_{}_4week_mae'.format(area, model)] = pred_4week_mae data_dict['x_4week'] = pd.to_datetime(pred_4week['x'].values) data_dict['x_64week'] = pd.to_datetime(pred_64week['x'].values) dates = data_dict['x_64week'] fig_predict = figure(title="predictions", tools=TOOLS, width=600, height=300, x_axis_type='datetime') mae_source_4week = ColumnDataSource(data=dict()) mae_source_64week = ColumnDataSource(data=dict()) columns = [ TableColumn(field="model", title="model Name"), TableColumn(field="mae", title="MAE") ] data_table_4week = DataTable(source=mae_source_4week, columns=columns, width=800) data_table_64week = DataTable(source=mae_source_64week, columns=columns, width=800) stats_4week = PreText(text='', width=500) stats_64week = PreText(text='', width=500) fig_predict_1year = figure(title="predictions_1year", tools=TOOLS, width=1000, height=300, x_axis_type='datetime', x_axis_location="above", background_fill_color="#efefef", x_range=(dates[0], dates[20])) select = figure( title= "Drag the middle and edges of the selection box to change the range above", plot_height=130, plot_width=1000, y_range=fig_predict_1year.y_range, x_axis_type="datetime", y_axis_type=None, tools="", toolbar_location=None, background_fill_color="#efefef") range_rool = RangeTool(x_range=fig_predict_1year.x_range) range_rool.overlay.fill_color = "navy" range_rool.overlay.fill_alpha = 0.2 for i, model in enumerate(models): model_cds[model] = {} model_cds[model]['cds_4week'] = ColumnDataSource(data={ 'x': [], 'y': [] }) model_cds[model]['cds_64week'] = ColumnDataSource(data={ 'x': [], 'y': [] }) fig_predict.line(x='x', y='y', source=model_cds[model]['cds_4week'], line_color=color_list[i], muted_color=color_list[i], line_width=2, line_alpha=0.7, legend=model) fig_predict_1year.line(x='x', y='y', source=model_cds[model]['cds_64week'], line_color=color_list[i], muted_color=color_list[i], line_width=2, line_alpha=0.7, legend=model) select.line('x', 'y', source=model_cds[model]['cds_64week'], line_color=color_list[i], muted_color=color_list[i]) select.ygrid.grid_line_color = None select.add_tools(range_rool) select.toolbar.active_multi = range_rool fig_config(fig_predict) fig_config(fig_predict_1year) p = figure(title="Taiwan", tools=TOOLS, x_axis_location=None, y_axis_location=None, width=600, height=800) p.background_fill_color = 'beige' p.border_fill_color = 'black' p.border_fill_alpha = 0.05 p.grid.grid_line_color = None p.toolbar.logo = None p.toolbar_location = None for i in range(22): twgeo_json['features'][i]['properties']['line_width'] = 0.5 twgeo_json['features'][i]['properties']['line_color'] = 'white' geo_source.geojson = json.dumps(twgeo_json) selected_g = Patches(fill_color='blue', line_color='white', line_width=4, line_alpha=0.5) renderer = p.patches('xs', 'ys', fill_alpha=0.7, fill_color='blue', line_color='line_color', line_width='line_width', line_alpha=1, source=geo_source) renderer.selection_glyph = selected_g p.add_tools(TapTool()) p.add_tools( HoverTool(tooltips=[("name", "@name"), ("index", "$index"), ("(Lon,Lat)", "($x, $y)")])) def my_tap_handler(attr, old, new): fig_config(fig_predict) idx = geo_source.selected.indices[0] area = twgeo_json['features'][idx]['properties']['area'] geo_source.selected.indices = area_dict[area]['area_idx'] for i in range(22): if twgeo_json['features'][i]['properties']['area'] == area: twgeo_json['features'][i]['properties']['line_width'] = 4 twgeo_json['features'][i]['properties']['line_color'] = 'black' else: twgeo_json['features'][i]['properties']['line_width'] = 0.5 twgeo_json['features'][i]['properties']['line_color'] = 'white' geo_source.geojson = json.dumps(twgeo_json) if area: temp_date_4week = data_dict['x_4week'] temp_date_64week = data_dict['x_64week'] temp_text_4week = '' for i, model in enumerate(models): temp_y_4week = data_dict['{}_{}_4week'.format(area, model)] temp_y_64week = data_dict['{}_{}_64week'.format(area, model)] model_cds[model]['cds_4week'].data = { 'x': temp_date_4week, 'y': temp_y_4week } model_cds[model]['cds_64week'].data = { 'x': temp_date_64week, 'y': temp_y_64week } stats_4week.text = area + '(last 4 weeks mae):\n' stats_64week.text = area + '(last one year mae):\n' mae_source_4week.data = { 'model': [model for model in models if model != 'truth'], 'mae': [ pred_4week_mae['{}_{}'.format(area, model)] for model in models if model != 'truth' ], } mae_source_64week.data = { 'model': [model for model in models if model != 'truth'], 'mae': [ pred_64week_mae['{}_{}'.format(area, model)] for model in models if model != 'truth' ], } geo_source.on_change('selected', my_tap_handler) layouts = column(fig_predict, stats_4week, data_table_4week) layouts = row(p, layouts) layouts = column(layouts, fig_predict_1year, select, stats_64week, data_table_64week) return layouts