def _plot_contour(self, p, contour_data, x_range, y_range): """Plot contour data. Parameters ---------- p: bokeh.plotting.figure figure to be drawn upon contour_data: Dict[str -> np.array] dict from labels to array with contour data x_range: List[float, float] min and max of x-axis y_range: List[float, float] min and max of y-axis Returns ------- handles: dict[str -> tuple(ImageGlyph, tuple(float, float))] mapping from label to image glyph and min/max-tuple """ unique = np.unique( np.concatenate( [contour_data[label][2] for label in contour_data.keys()])) color_mapper = LinearColorMapper(palette="Viridis256", low=np.min(unique), high=np.max(unique)) handles = {} default_label = 'combined' if 'combined' in contour_data.keys( ) else list(contour_data.keys())[0] for label, data in contour_data.items(): unique = np.unique(contour_data[label][2]) handles[label] = (p.image(image=contour_data[label], x=x_range[0], y=y_range[0], dw=x_range[1] - x_range[0], dh=y_range[1] - y_range[0], color_mapper=color_mapper), (np.min(unique), np.max(unique))) if not label == default_label and len(contour_data) > 1: handles[label][0].visible = False color_bar = ColorBar(color_mapper=color_mapper, ticker=BasicTicker(desired_num_ticks=15), label_standoff=12, border_line_color=None, location=(0, 0)) color_bar.major_label_text_font_size = '12pt' p.add_layout(color_bar, 'right') return handles, color_mapper
def make_plot(): # Use LinearColorMapper that linearly maps a range of numbers into a sequence of colors color_mapper = LinearColorMapper(palette=palette, low=min(agg_data['description']), high=max(agg_data['description'])) # Create color bar. format_tick = NumeralTickFormatter(format='0,0') color_bar = ColorBar(color_mapper=color_mapper, label_standoff=18, formatter=format_tick, border_line_color=None, location=(0, 0)) color_bar.major_label_text_font_size = '8pt' p = figure(title='Offence by Neighborhood in Chicago 2019', plot_height=650, plot_width=650, toolbar_location=None) # Add patch renderer to figure. p.patches('xs', 'ys', source=geosource, fill_color={ 'field': 'description', 'transform': color_mapper }, line_color='grey', line_width=0.25, fill_alpha=1) #Add hover tool to view neighborhood stats hover = HoverTool(tooltips=[( 'community', '@community'), ('community_area#', '@community_area'), ('#crimes', '@description{,}')]) style(p) p.axis.visible = False # Specify color bar layout. p.add_layout(color_bar, 'right') # Add the hover tool to the graph p.add_tools(tap, hover) return p
def _plot_contour(self, p, contour_data, x_range, y_range): """Plot contour data. Parameters ---------- p: bokeh.plotting.figure figure to be drawn upon contour_data: np.array array with contour data x_range: List[float, float] min and max of x-axis y_range: List[float, float] min and max of y-axis Returns ------- p: bokeh.plotting.figure modified figure handle """ min_z = np.min(np.unique(contour_data[2])) max_z = np.max(np.unique(contour_data[2])) color_mapper = LinearColorMapper(palette="Viridis256", low=min_z, high=max_z) p.image(image=contour_data, x=x_range[0], y=y_range[0], dw=x_range[1] - x_range[0], dh=y_range[1] - y_range[0], color_mapper=color_mapper) color_bar = ColorBar(color_mapper=color_mapper, ticker=BasicTicker(desired_num_ticks=15), label_standoff=12, border_line_color=None, location=(0, 0)) color_bar.major_label_text_font_size = '12pt' p.add_layout(color_bar, 'right') return p
def create_figure(m, m_source, columns): print("creating figure with x = %s, y = %s, color = %s, size = %s" % (x.value, y.value, color.value, size.value)) tooltips = [("id", "@id"), (x.value, "@{%s}" % x.value), (y.value, "@{%s}" % y.value)] if color.value != 'None': tooltips += [(color.value, "@{%s}" % color.value)] if size.value != 'None': tooltips += [(size.value, "@{%s}" % size.value)] x_range = range_defaults[x.value] if x.value in range_defaults else None y_range = range_defaults[y.value] if y.value in range_defaults else None p = figure(plot_height=800, plot_width=800, x_range=x_range, y_range=y_range, tooltips=tooltips, tools=["tap", "hover", "box_select", "reset", "save"], title=("%s: %s vs %s" % (data.value, y.value, x.value))) p.xaxis.axis_label = x.value p.yaxis.axis_label = y.value sz = 8 print("size.value = '%s'" % size.value) if size.value != 'None': if (size.value + "_plotsize") in m: sz = size.value + "_plotsize" else: sz = size.value print(sz) mapper = None c = "#31AADE" if color.value != 'None': if color.value in colormap_overrides: colormap_args = colormap_overrides[color.value] else: colormap_args = dict(palette=Viridis5) if 'low' not in colormap_args: colormap_args['low'] = m[color.value].min() if 'high' not in colormap_args: colormap_args['high'] = m[color.value].max() print(color.value, colormap_args) mapper = linear_cmap(field_name=color.value, **colormap_args) c = mapper p.circle(x=x.value, y=y.value, color=c, size=sz, line_color=c, alpha=0.4, hover_color='white', hover_alpha=0.7, source=m_source) fs = "1.3em" if mapper: color_bar = ColorBar(color_mapper=mapper['transform'], width=8, location=(0, 0)) color_bar.major_label_text_font_size = fs color_bar.major_label_text_align = "left" p.add_layout(color_bar, 'right') p.yaxis.axis_label_text_font_size = fs p.yaxis.major_label_text_font_size = fs p.xaxis.axis_label_text_font_size = fs p.xaxis.major_label_text_font_size = fs p.title.text_font_size = fs return p
def function_source(attr, old, new): selected_index = source.selected.indices[0] crime_type = df2.iloc[selected_index]['primary_type'] subset = df2.loc[df2['primary_type'] == crime_type] # Merge geojson map file with community level aggregated crime data merged_df1 = cg.merge(subset, how='left', right_on='community_area', left_on='area_num_1') # Bokeh uses geojson formatting, representing geographical features, with json # Convert to json merged_json1 = json.loads(merged_df1.to_json()) json_data1 = json.dumps(merged_json1) # Input geojson source that contains features for plotting for geosource1 = GeoJSONDataSource(geojson=json_data1) # Use LinearColorMapper that linearly maps a range of numbers into a sequence of colors. color_mapper = LinearColorMapper(palette=palette, low=min(subset['case_number']), high=max(subset['case_number'])) # Create color bar format_tick = NumeralTickFormatter(format='0,0') color_bar = ColorBar(color_mapper=color_mapper, label_standoff=18, formatter=format_tick, border_line_color=None, location=(0, 0)) color_bar.major_label_text_font_size = '8pt' p = figure(title=' Offence by Neighborhood in Chicago 2019 - {}'.format( crime_type), plot_height=650, plot_width=650, toolbar_location=None) # Add patch renderer to figure p.patches('xs', 'ys', source=geosource1, fill_color={ 'field': 'case_number', 'transform': color_mapper }, line_color='grey', line_width=0.25, fill_alpha=1) #Add hover tool to view neighborhood stats hover = HoverTool(tooltips=[( 'community', '@community'), ('community_area#', '@community_area'), ('#crimes', '@case_number{,}')]) style(p) p.axis.visible = False # Specify color bar layout p.add_layout(color_bar, 'right') # Add the hover tool to the graph p.add_tools(tap, hover) layout.children[0] = p
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
p.title.text_color = "orange" p.title.text_font_size = "25px" p.xaxis.axis_label = 'dBZ' p.yaxis.axis_label = 'Height(km)' color_mapper = LogColorMapper(palette="Spectral11", low=1, \ high=max(bins.counts)) from bokeh.transform import linear_cmap, log_cmap linearc=log_cmap('counts', 'Spectral11', 1, max(bins.counts)) p.hex_tile(q="q", r="r", size=0.5, line_color=None, source=bins, fill_color=linearc) color_mapper = LogColorMapper(palette="Spectral11", low=1, high=max(bins.counts)) color_bar = ColorBar(color_mapper=color_mapper, ticker=LogTicker(), label_standoff=12, border_line_color=None, location=(0,0)) color_bar.major_label_text_font_size="20pt" color_bar.title="Counts" color_bar.title_text_font_size="20pt" p.add_layout(color_bar, 'right') bokeh.io.export_png(p, filename="cfadKa_att.png") bokeh.io.output_file("hex_tile.html") bokeh.io.show(p) bins2 = bokeh.util.hex.hexbin( z3dm[:,:,:,0].T.flatten(),\ h[1:,:,nx1:nx2].flatten(),\ 0.5) from bokeh.models import Range1d, LogColorMapper, LogTicker, ColorBar
def make_maps(self, lng_center=-122.439308, lat_center=37.754899, zoom_level=12, resp_time_colorbar_min=2, resp_time_colorbar_max=98, density_colorbar_min=5, density_colorbar_max=95, density_patch_alpha=0.5, resptime_patch_alpha=0.5, figs_output_dir='', scripts_output_dir='', div_output_dir='', plot_width=750, plot_height=600, ): """Plot maps of response time and medical incident density.""" try: with open('tract_dict.p', 'rb') as f: tract_dict = pickle.load(f) with open('year_dict.p', 'rb') as f: year_dict = pickle.load(f) except: tract_dict = self._build_tract_dict() year_dict = self._build_year_dict(tract_dict) with open('year_dict.p', 'wb') as f: pickle.dump(year_dict, f) with open('tract_dict.p', 'wb') as f: pickle.dump(tract_dict, f) for yr in range(self.min_year, self.max_year + 1): density_color_map = 'Inferno256' tools = 'pan,wheel_zoom,reset,save' density_map_options = GMapOptions( lat=lat_center, lng=lng_center, map_type='roadmap', zoom=zoom_level, ) col_data_source = self._build_data_source( year=yr, tract_dict=tract_dict, year_dict=year_dict, ) col_data_source['response_time_str'] = [ str(round(x, 1)) for x in col_data_source['response_time'] ] col_data_source['num_incidents_str'] = [ str(round(x, 1)) for x in col_data_source['num_incidents'] ] source = ColumnDataSource(col_data_source) # ------------------------------------------------------------------ # MAP INCIDENT DENSITY output_file(figs_output_dir + f"density_map_{yr}.html") density_plot = gmap( GMAP_API_KEY, density_map_options, width=750, height=600, tools=tools, toolbar_location='above' ) tooltips = """ <div style="width: 13em; heigh: 3em; word-wrap: break-word; margin: 0px 0px 0px 5px"> <div> <span style="font-size: 13px; color: #A9A9A9; background-color: #FFFFFF;"> Medical Incident Density </span> </div> <div style="margin-top:0.5em;"> <span style="font-size: 13px; color: #000000; background-color: #FFFFFF;"> <b>Tract @tract_name</b> <br> @num_incidents_str per 100,000 sq feet </span> </div> </div> """ density_plot.add_tools(HoverTool(tooltips=tooltips)) min_color_val = np.percentile( col_data_source['num_incidents'], density_colorbar_min, ) max_color_val = np.percentile( col_data_source['num_incidents'], density_colorbar_max ) color_mapper = LogColorMapper( palette=density_color_map, low=min_color_val, high=max_color_val, ) color_bar = ColorBar( color_mapper=color_mapper, label_standoff=10, border_line_color=None, location=(1,0), ticker=FixedTicker(ticks=[0.2, 1, 2, 4, 8, 16, 32, 64]) ) density_plot.add_layout(color_bar, 'right') density_plot.patches( 'x', 'y', source=col_data_source, fill_color=linear_cmap( 'num_incidents', density_color_map, min_color_val, max_color_val ), fill_alpha=density_patch_alpha, line_color="black", line_width=1 ) density_plot.yaxis.major_label_text_font_size = '10pt' density_plot.xaxis.major_label_text_font_size = '10pt' color_bar.major_label_text_font_size = '12pt' color_bar.major_label_text_font_style = 'italic' save(density_plot) script, div = components(density_plot) with open( scripts_output_dir + f"density_map_script_{yr}.js", 'w' ) as f: f.write(script) with open( div_output_dir + f"density_map_div_{yr}.html", 'w' ) as f: f.write(div) # ------------------------------------------------------------------ # MAP RESPONSE TIMES output_file(figs_output_dir + f"resp_time_map_{yr}.html") resptime_map_options = GMapOptions( lat=density_map_options.lat, lng=density_map_options.lng, map_type='roadmap', zoom=density_map_options.zoom, ) resptime_plot = gmap( GMAP_API_KEY, resptime_map_options, width=plot_width, height=plot_height, tools=tools, toolbar_location='above', ) tooltips = """ <div style="width: 12em; heigh: 3em; word-wrap: break-word; margin: 0px 0px 0px 5px"> <div> <span style="font-size: 13px; color: #A9A9A9; background-color: #FFFFFF;"> Median Response Time </span> </div> <div style="margin-top:0.5em;"> <span style="font-size: 13px; color: #000000; background-color: #FFFFFF;"> <b>Tract @tract_name</b> <br> @response_time_str minutes </span> </div> </div> """ resptime_plot.add_tools(HoverTool(tooltips=tooltips)) source = ColumnDataSource(col_data_source) resptime_color_map = 'Inferno256' min_color_val = np.percentile( col_data_source['response_time'], resp_time_colorbar_min, ) max_color_val = np.percentile( col_data_source['response_time'], resp_time_colorbar_max, ) color_mapper = LinearColorMapper( palette=resptime_color_map, low=min_color_val, high=max_color_val, ) color_bar = ColorBar( color_mapper=color_mapper, ticker=BasicTicker(), label_standoff=10, border_line_color=None, location=(1,0), ) resptime_plot.add_layout(color_bar, 'right') resptime_plot.patches( 'x', 'y', source=col_data_source, fill_color=linear_cmap( 'response_time', resptime_color_map, min_color_val, max_color_val ), fill_alpha=resptime_patch_alpha, line_color="black", line_width=1 ) resptime_plot.yaxis.major_label_text_font_size = '10pt' resptime_plot.xaxis.major_label_text_font_size = '10pt' color_bar.major_label_text_font_size = '12pt' color_bar.major_label_text_font_style = 'italic' save(resptime_plot) script, div = components(resptime_plot) with open( scripts_output_dir + f"resp_time_map_script_{yr}.js", 'w' ) as f: f.write(script) with open( div_output_dir + f"resp_time_map_div_{yr}.html", 'w' ) as f: f.write(div)