def test_cmap_generator_function(): assert pal.viridis(256) == pal.Viridis256 assert pal.magma(256) == pal.Magma256 assert pal.plasma(256) == pal.Plasma256 assert pal.inferno(256) == pal.Inferno256 assert pal.gray(256) == pal.Greys256 assert pal.grey(256) == pal.Greys256
def test_cmap_generator_function(): assert pal.viridis(256) == pal.Viridis256 assert pal.magma(256) == pal.Magma256 assert pal.plasma(256) == pal.Plasma256 assert pal.inferno(256) == pal.Inferno256 assert pal.gray(256) == pal.Greys256 assert pal.grey(256) == pal.Greys256 assert pal.turbo(256) == pal.Turbo256 assert pal.diverging_palette(pal.Reds9, pal.Greys9, n=18, midpoint=0.5) == pal.Reds9 + pal.Greys9[::-1]
def IMG_plot(gid): IMG = np.load('../bokeh_app/data/imgs/{}_img.npy'.format(gid)) img = figure(plot_width=300, plot_height=225, x_range=(0, 10), y_range=(0, 10), tools = '') img.image(image=[IMG], x=0, y=0, dw=10, dh=10,palette=palettes.gray(100)) img.title.text_font_size = "20pt" img.xaxis.major_label_text_color = img.yaxis.major_label_text_color = None img.yaxis.major_tick_line_color = img.xaxis.major_tick_line_color =None img.yaxis.minor_tick_line_color = img.xaxis.minor_tick_line_color =None return img
def _create_choropleth_map(source, width=600, height=1000): """ Create a choropleth map with of incidents in Amsterdam-Amstelland. params ------ source: a Bokeh GeoJSONDataSource object containing the data return ------ a Bokeh figure showing the spatial distribution of incidents in over the region """ map_colors = ['#f2f2f2', '#fee5d9', '#fcbba1', '#fc9272', '#fb6a4a', '#de2d26'] color_mapper = LogColorMapper(palette=map_colors) nonselection_color_mapper = LogColorMapper(palette=gray(6)[::-1]) tooltip_info = [("index", "$index"), ("(x,y)", "($x, $y)"), ("#incidents", "@incident_rate"), ("location id", "@location_id")] map_tools = "pan,wheel_zoom,tap,hover,reset" # get google maps API key with open("./Data/googlemapskey.txt") as f: maps_api_key = f.readline() map_options = GMapOptions(lat=52.35, lng=4.9, map_type="roadmap", zoom=11) p = gmap(maps_api_key, map_options,tools=map_tools, plot_width=width, plot_height=height, x_axis_location=None, y_axis_location=None) p.xaxis.visible=False p.yaxis.visible=False # p = figure(title="Spatial distribution of incidents in Amsterdam-Amstelland", # tools=map_tools, x_axis_location=None, y_axis_location=None, # height=height, width=width, tooltips=tooltip_info) # p.x_range = Range1d(4.66, 5.10) # p.y_range = Range1d(52.18, 52.455) # p.grid.grid_line_color = None # p.add_tile(CARTODBPOSITRON) patches = p.patches('xs', 'ys', source=source, fill_color={'field': 'incident_rate', 'transform': color_mapper}, fill_alpha=0.5, line_color="black", line_width=0.3, nonselection_fill_color={'field': 'incident_rate', 'transform': nonselection_color_mapper}) return p, patches
def prepare_and_draw_matrix(dh_mat2, heading_list, disc_list, outfile): totals = {} for d in disc_list: total = 0 for h in heading_list: if( dh_mat2[h].get(d, None) is not None): total += dh_mat2[h][d] totals[d] = total section = [] d_type = [] percent = [] for d in disc_list: for h in heading_list: if( dh_mat2[h].get(d, None) is None): section.append(h) d_type.append(d) percent.append(0.0) else : section.append(h) d_type.append(d) percent.append(100.0 * dh_mat2[h][d] / totals[d]) data = {'Section': section, 'Discourse Type': d_type, 'Percentage': percent } color = ColorAttr(bin=True, palette=gray(6), sort=True, ascending=False) hm = HeatMap(data, x='Discourse Type', y='Section', values='Percentage', stat=None, plot_height=260, legend=False, color=color) output_file(outfile+'1.html', mode='cdn', root_dir=None) save(hm) hm1 = HeatMap(data, x='Discourse Type', y='Section', values='Percentage', stat=None, plot_height=260, legend=True, color=color) output_file(outfile+'2.html', mode='cdn', root_dir=None) save(hm1) '''
def create_world_cases_time_series_tab(): ## Data Sources source_df, source_CDS = get_country_cases_vs_time() ## Line Plots line_figure = figure( x_axis_type='datetime', y_axis_type='log', title='World Confirmed Cases by Region', x_axis_label='Date', y_axis_label='Number of Confirmed Cases (Logarithmic Scale)', active_scroll='wheel_zoom') starting_regions = ['China', 'US', 'Italy'] excluded_columns_set = {'index', 'date'} doubling_lines_props = { 'alpha': 0.6, 'muted_alpha': 0.2, 'line_width': 3, 'source': source_CDS, 'x': 'date', 'visible': True } for number, text, color in zip([4, 7, 14], ['four', 'seven', 'fourteen'], gray(6)[2:5]): column_name = f'{text}_day_doubling' excluded_columns_set.add(column_name) source_CDS.data[column_name] = 2**( np.arange(len(source_CDS.data['index'])) / number) line_figure.line(y=column_name, legend_label=f'{number}-day Doubling Time', line_color=color, name=column_name, **doubling_lines_props) line_params = { 'x': 'date', 'source': source_CDS, 'line_width': 4, 'alpha': 0.6 } lines = { key: line_figure.line(y=key, name=key, line_color=color, **line_params) for key, color in zip(starting_regions, viridis(len(starting_regions))) } line_figure.legend.location = 'top_left' line_figure.legend.click_policy = 'hide' hover_tool = HoverTool( tooltips=[('Date', '@date{%F}'), ('Region', '$name'), ('Number of Cases', '@$name{0,0}')], formatters={ '@date': 'datetime', }, renderers=[*line_figure.renderers], # mode='vline' ) line_figure.add_tools(hover_tool) ## Region Selector labels = [ key for key in source_CDS.data.keys() if key not in excluded_columns_set ] def region_select_callback(attr, old, new): new_lines = set(new) - set(old) old_lines = set(old) - set(new) for key in old_lines: lines[key].visible = False for key in new_lines: if key in lines.keys(): lines[key].visible = True else: lines[key] = line_figure.line( y=key, name=key, line_color=np.random.choice(Viridis256), **line_params) hover_tool.renderers = [*hover_tool.renderers, lines[key]] region_select = MultiSelect(title='Select Regions to Show', value=starting_regions, options=labels, sizing_mode='stretch_height') region_select.on_change('value', region_select_callback) ## Create Layout child = row([ column([line_figure]), column([region_select]), ]) return Panel(child=child, title='World Cases Time Series')
def make_postage_stamp_plot(self, index, stamp_size=100, reverse_colormap=False): """ Gather the data for creating the source postage stamp plot. Parameters ---------- index : int The location of the source data in the Source table. stamp_size : int, optional Size of the generated postage stamp in pixels. reverse_colormap : bool, optional Reverse the colormap. Default is black (low) to white (high). """ ra_target, dec_target = ( self.src['coord_ra'][self.good_indexes][index], self.src['coord_dec'][self.good_indexes][index]) # Radians radec = afwGeom.SpherePoint(ra_target, dec_target, afwGeom.radians) cutoutSize = afwGeom.ExtentI(stamp_size, stamp_size) wcs = self.calexp.getWcs() # Note: This call fails in version 15.0. Requires a weekly after that release. xy = afwGeom.PointI(wcs.skyToPixel(radec)) bbox = afwGeom.BoxI(xy - cutoutSize // 2, cutoutSize) # Check for bounds that fall off the edges of the image. Need to clip them to the # image boundary otherwise the calexp_sub call fails. calexp_extent = self.calexp.getDimensions() clipped_bbox = afwGeom.BoxI(afwGeom.PointI(0, 0), calexp_extent) clipped_bbox.clip(bbox) # Postage stamp image only cutout_image = self.butler.get('calexp_sub', bbox=clipped_bbox, immediate=True, dataId=self.dataid).getMaskedImage() vmin, vmax = self.zscale.get_limits(cutout_image.image.array) self.image_src.data = { 'img': [cutout_image.image.array], 'x': [0], 'y': [0], 'dw': [clipped_bbox.getDimensions().getX()], 'dh': [clipped_bbox.getDimensions().getY()] } gc = gray(256) if reverse_colormap: gc.reverse() lcm = LinearColorMapper(palette=gc, low=vmin, high=vmax) self.img_plt.image('img', 'x', 'y', 'dw', 'dh', color_mapper=lcm, source=self.image_src) # Color bar doesn't come up properly. Need to work on this later. colorbar = ColorBar(color_mapper=lcm, ticker=BasicTicker(), border_line_color=None, label_standoff=5, location=(0, 0)) # self.img_plt.add_layout(colorbar, 'right') # Does the cutout_image have a wcs? It does not appear to... self.img_plt.circle(xy.getX() - cutout_image.getX0(), xy.getY() - cutout_image.getY0(), fill_color=None, line_color='red', radius=int(0.05 * stamp_size))
"numba is not installed. This example will be painfully slow.") njit = lambda f: f from bokeh.io import curdoc from bokeh.layouts import column from bokeh.models import ColumnDataSource, Slider from bokeh.palettes import gray from bokeh.plotting import figure image = scipy.misc.ascent().astype(np.int32)[::-1, :] w, h = image.shape source = ColumnDataSource(data=dict(image=[image])) p = figure(x_range=(0, w), y_range=(0, h)) p.image('image', x=0, y=0, dw=w, dh=h, palette=gray(256), source=source) @njit def blur(outimage, image, amt): for i in range(amt, w - amt): for j in range(amt, h - amt): px = 0. for iw in range(-amt // 2, amt // 2): for jh in range(-amt // 2, amt // 2): px += image[i + iw, j + jh] outimage[i, j] = px / (amt * amt) def update(attr, old, new): out = image.copy()
def guide_star_timelapse(image_data, height=170, width=170, title=None, ncols=8): ''' Args: image_data: dictionary containing guide-rois image data Options: height: height of plot (default = 300) width: width of plot (default = 300) title: title of plot, only needed if you want a different one than is hardcoded(default = None) Returns bokeh layout object.''' scaled_data = subtract_medians(image_data, return_medians=False) #get dictionary of angles to rotate different GFAs to align images along same axis gfa_file = os.path.expandvars('$DESIMODEL/data/focalplane/gfa.ecsv') rotdict = rot_dict(gfa_file) #rotate images scaled_data = rotate_guide_images(scaled_data, rotdict) #data to rescale colors later for readability zmin, zmax = np.percentile(get_all_values(scaled_data), (1, 99)) keys = list(scaled_data.keys()) indices = range(len(scaled_data[keys[0]])) sources = {} for idx in indices: imgs = [] image_names = [] for key in keys: img = scaled_data[key][idx] u8img = (255*(img.clip(zmin, zmax) - zmin) / (zmax-zmin)).astype(np.uint8) colormap = LinearColorMapper(palette=gray(256), low=0, high=255) imgs.append([u8img]) image_names.append(key) sources['_' + str(idx)] = ColumnDataSource(data = dict(zip( [name for name in image_names], [img for img in imgs], ))) dict_of_sources = dict(zip( [idx for idx in indices], ['_%s' % idx for idx in indices] )) js_source_array = str(dict_of_sources).replace("'", "") renderer_source = sources['_%s' % indices[0]] ims = [] im_glyphs = [] im_renderers = [] for key in keys: name_key = key title = 'Cam {} Star {}'.format(key[5], key[7]) im = bk.figure(plot_width=width, plot_height=height+15, x_range = (0, 50), y_range=(0, 50), title=title) im.xaxis.visible = False im.yaxis.visible = False im_glyph = Image(image=name_key, x=0, y=0, dw=50, dh=50) im_renderer = im.add_glyph(renderer_source, im_glyph) ims.append(im) im_glyphs.append(im_glyphs) im_renderers.append(im_renderer) code = """ var idx = cb_obj.value, sources = %s, new_source_data = sources[idx].data; renderer_source.data = new_source_data; """ % js_source_array callback = CustomJS(args=sources, code=code) slider = Slider(start=0, end=indices[-1], value=0, step=1, title="Frame", width=width*4) callback.args['renderer_source'] = renderer_source callback.args['slider'] = slider slider.js_on_event('value', callback) ims_plot = gridplot(ims, ncols=ncols, toolbar_location=None) layout = column([slider, ims_plot]) return layout
def render_reads(self, render_all=False): read_dict = { "center": [], "r_id": [], "r_name": [], "size": [], "q": [], "r": [], "l": [], "idx": [], "c": [], "oc": [], "f": [], "layer": [], "palindrome": [], "overlapping": [], "in_soc_reseed": [], "soc_nt": [], "soc_id": [], "max_filter": [], "min_filter": [], "x": [], "y": [], "category": [] } # create a column data source for the read plot... read_ambiguous_reg_dict = { "l": [], "r": [], "t": [], "b": [], "f": [], "s": [] } read_id_n_cols = {} col_ids = [] all_col_ids = [] category_counter = 0 end_column = None if not self.selected_read_id is None: self.read_ids.add(self.selected_read_id) for idx in self.widgets.get_forced_read_ids(self): self.read_ids.add(idx) if len(self.read_ids) > 0: with self.measure("computing seeds"): if self.do_render_seeds: info_ret = seedDisplaysForReadIds(self.params, self.db_pool, self.read_ids, self.pack, self.mm_index, self.mm_counter, len(self.read_ids) > self.do_compressed_seeds, # 0 == infinite time for computing 3*self.get_max_num_ele()//10 if not render_all else 0) with self.measure("render seeds"): if (self.do_render_seeds and len(info_ret.vRet) < self.get_max_num_ele() * 10) or render_all: for seed_info in info_ret.vRet: read_dict["r_id"].append(seed_info.iReadId) read_dict["r_name"].append(seed_info.sReadName) read_dict["size"].append(seed_info.uiSize) read_dict["l"].append(seed_info.uiL) read_dict["q"].append(seed_info.uiQ) read_dict["idx"].append(seed_info.uiSeedOrderOnQuery) read_dict["layer"].append(seed_info.uiLayer) read_dict["palindrome"].append(seed_info.bParlindrome) read_dict["overlapping"].append(seed_info.bOverlapping) read_dict["in_soc_reseed"].append(seed_info.bInSocReseed) read_dict["soc_nt"].append(seed_info.soc_nt) read_dict["soc_id"].append(seed_info.soc_id) read_dict["max_filter"].append(seed_info.uiMaxFilterCount) read_dict["min_filter"].append(seed_info.uiMinFilterCount) read_dict["f"].append(seed_info.bOnForward) read_dict["category"].append(seed_info.uiCategory) read_dict["center"].append(seed_info.fCenter) read_dict["r"].append(seed_info.uiR) read_dict["x"].append([*seed_info.xX]) read_dict["y"].append([*seed_info.xY]) read_dict["c"].append("lightgrey") read_dict["oc"].append(gray(6)[ (seed_info.soc_id % 5) + 1]) for read in info_ret.vReads: self.read_plot.nuc_plot.nucs_by_r_id[read.id] = {"p": [], "c": [], "i": []} self.read_plot_rects[read.id] = {"l": [], "b": [], "t": [], "r": [], "f":[], "s":[], "k":[], "c":[], "dp": [], "i_soc": [], "layer":[]} for y, nuc in enumerate(str(read)): append_nuc_type(self.read_plot.nuc_plot.nucs_by_r_id[read.id], nuc, y, "p") for x, y in info_ret.vReadsNCols: read_id_n_cols[x] = y col_ids = [*info_ret.vColIds] all_col_ids = [*info_ret.vAllColIds] for r_i in info_ret.vRectangles: for rectangle, layer, fill, seed_sample_size, k_mer_size, use_dp in zip(r_i.vRectangles, r_i.vRectangleLayers, r_i.vRectangleFillPercentage, r_i.vRectangleReferenceAmbiguity, r_i.vRectangleKMerSize, r_i.vRectangleUsedDp): self.add_rectangle(seed_sample_size, r_i.iReadId, rectangle, fill, read_ambiguous_reg_dict, r_i.uiEndColumnSize, r_i.uiCategory, k_mer_size, use_dp, r_i.bInSoCReseeding, layer) else: print("gave up rendering reads") def callback(): with self.measure("rendering seeds"): # render ambiguous regions on top and left self.seed_plot.ambiguous_regions.data = read_ambiguous_reg_dict # render seeds on top and left self.seed_plot.seeds.data = read_dict if self.seed_plot.left_plot.x_range.start == 0 and self.seed_plot.left_plot.x_range.end == 0: self.seed_plot.left_plot.x_range.start = -1 self.seed_plot.left_plot.x_range.end = category_counter if len(self.read_ids) <= self.do_compressed_seeds: self.seed_plot.left_plot.xaxis.ticker = FixedTicker(ticks=col_ids) self.seed_plot.bottom_plot.yaxis.ticker = FixedTicker(ticks=col_ids) self.seed_plot.left_plot.xaxis.formatter = FuncTickFormatter( args={"read_id_n_cols": read_id_n_cols}, code=""" if(!tick in read_id_n_cols) return ""; return read_id_n_cols[tick]; """) self.seed_plot.bottom_plot.yaxis.formatter = FuncTickFormatter( args={"read_id_n_cols": read_id_n_cols}, code=""" if(!tick in read_id_n_cols) return ""; return read_id_n_cols[tick]; """) self.seed_plot.left_plot.xaxis.axis_label = "Read Id" self.seed_plot.bottom_plot.yaxis.axis_label = "Read Id" else: self.seed_plot.left_plot.xaxis.ticker = [] self.seed_plot.left_plot.xaxis.axis_label = "compressed seeds" self.seed_plot.bottom_plot.yaxis.ticker = [] self.seed_plot.bottom_plot.yaxis.axis_label = "compressed seeds" self.seed_plot.left_plot.xgrid.ticker = FixedTicker(ticks=all_col_ids) self.seed_plot.bottom_plot.ygrid.ticker = FixedTicker(ticks=all_col_ids) self.seed_plot.update_selection(self) self.do_callback(callback)
def show_pdf_heatmap_compute_pdf_fun(self, compute_pdf_fun, title, paper = False,x_fixed=None, y_fixed=None, x_lim=None, y_lim=None,pdf_percentile_cut_off=None): dl = self.data_loader grid_size=100 grids = [] for i, val in enumerate(x_fixed): if val is None: grids.append(np.linspace(dl.min_x[i], dl.max_x[i], grid_size)) for i, val in enumerate(y_fixed): if val is None: grids.append(np.linspace(dl.min_y[i], dl.max_y[i], grid_size)) mesh = np.meshgrid(*(grids)) x_min = np.min(mesh[0]) x_max = np.max(mesh[0]) y_min = np.min(mesh[1]) y_max = np.max(mesh[1]) xs = [] ys = [] mesh_id=0 for i, val in enumerate(x_fixed): if val is None: xs.append(mesh[mesh_id].reshape(-1,1)) mesh_id+=1 else: xs.append(np.ones((grid_size*grid_size, 1)) * val) for i, val in enumerate(y_fixed): if val is None: ys.append(mesh[mesh_id].reshape(-1,1)) mesh_id+=1 else: ys.append(np.ones((grid_size*grid_size, 1)) * val) pdf = compute_pdf_fun(np.concatenate(xs, axis=1), np.concatenate(ys, axis=1)) print("integral: %f"% ( np.sum(pdf)/(grid_size*grid_size))) if pdf_percentile_cut_off is None: high=np.max(pdf) else: high=np.percentile(pdf, 95) color_mapper = LogColorMapper(palette=gray(256),low=np.min(pdf), high=high) # color_mapper = LinearColorMapper(palette=gray(256),low=np.min(pdf), high=high) if paper: p = figure(x_range=(x_min, x_max), y_range=(y_min, y_max), tooltips=[("x", "$x"), ("y", "$y"), ("value", "@image")],toolbar_location = None) else: p = figure(x_range=(x_min, x_max), y_range=(y_min, y_max), title=title, tooltips=[("x", "$x"), ("y", "$y"), ("value", "@image")]) # p.xaxis.axis_label = 'x%d' % x_i # p.yaxis.axis_label = 'y%d' % y_i p.xaxis.axis_label_text_font_size = "20pt" p.yaxis.axis_label_text_font_size = "20pt" p.xaxis.major_label_text_font_size="20pt" p.yaxis.major_label_text_font_size = "20pt" p.image(image=[pdf.reshape(grid_size, grid_size)], x=x_min, y=y_min,dw=x_max - x_min,dh=y_max - y_min,color_mapper=color_mapper) # color_bar = ColorBar(color_mapper=color_mapper, ticker=LogTicker(), # label_standoff=12, border_line_color=None, location=(0, 0)) # p.add_layout(color_bar, 'right') show(p); return p
def _im_setup(self, im, fig): from bokeh.models import LinearColorMapper # Defer slow imports _im = im assert _im.ndim == 2 ustack = self._u_stack() y = 0 if ustack.get("_flip_y"): assert "f_y_range" not in ustack _im = np.flip(_im, axis=0) y = _im.shape[0] dim = HW(_im.shape) if dim.w == 0 or dim.h == 0: # Deal with zero dims gracefully dim = HW(max(1, dim.h), max(1, dim.w)) _im = np.zeros(dim) full_w, full_h = (ustack.get("_full_w", False), ustack.get("_full_h", False)) if ustack.get("_full"): full_w, full_h = (True, True) if full_h: full_h = dim.h + 40 # TASK: This value is weird, need a way to derive it if ustack.get("_min_h") is not None: full_h = max(full_h, ustack.get("_min_h")) if full_w: full_w = dim.w + 20 # TASK: This value is weird, need a way to derive it if ustack.get("_min_w") is not None: full_w = max(full_w, ustack.get("_min_w")) _nan = ustack.get("_nan") if _nan is not None: _im = np.nan_to_num(_im) _cper = ustack.get("_cper") if _cper is not None: # color by percentile assert isinstance(_cper, tuple) and len(_cper) == 2 low, high = np.nanpercentile(_im, _cper) else: _cspan = ustack.get("_cspan") if _cspan is None: low = 0.0 if _im.shape[0] == 0: high = 1.0 else: with warnings.catch_warnings(): warnings.filterwarnings("error") try: high = np.nanmean(_im) + np.nanstd(_im) * 4 except Exception: high = 1.0 else: if isinstance(_cspan, (list, tuple)): assert len(_cspan) == 2 low = _cspan[0] high = _cspan[1] elif isinstance(_cspan, np.ndarray): assert _cspan.shape == (2,) low = _cspan[0] high = _cspan[1] else: assert isinstance(_cspan, (int, float)) low = 0 high = _cspan pal = ustack.get("_palette", "viridis") if pal == "viridis": from bokeh.palettes import viridis pal = viridis(256) elif pal in ("gray", "grey",): from bokeh.palettes import gray pal = gray(256) elif pal == "inferno": from bokeh.palettes import inferno pal = inferno(256) # zero_color = ustack.get("_zero_color") # if zero_color is not None: # pal = copy.copy(pal) # pal[0] = zero_color cmap = LinearColorMapper(palette=pal, low=low, high=high) if full_w: fig.plot_width = full_w if full_h: fig.plot_height = full_h return dim, cmap, _im, y
def generate_correlation_graph(correlation_matrix_csv_path, path_to_save, title='Correlation Matrix',plot_height=1000, plot_width=1600): ## PREPARING CORRELATION MATRIX df = pd.read_csv(correlation_matrix_csv_path) df = df.set_index('Unnamed: 0').rename_axis('parameters', axis=1) df.index.name = 'level_0' ## AXIS LABELS FOR PLOT common_axes_val = list(df.index) df = pd.DataFrame(df.stack(), columns=['correlation']).reset_index() source = ColumnDataSource(df) ## FINDING LOWEST AND HIGHEST OF CORRELATION VALUES low_df_corr_min = df.correlation.min() high_df_corr_min = df.correlation.max() no_of_colors = len(df.correlation.unique()) ### PLOT PARTICULARS ## CHOOSING DEFAULT COLORS mapper = LinearColorMapper(palette=get_reversed_list(cividis(no_of_colors)), low=low_df_corr_min, high=high_df_corr_min) ## SETTING UP THE PLOT p = figure(title=title,x_range=common_axes_val, y_range=list((common_axes_val)),x_axis_location="below", plot_width=plot_width, plot_height=plot_height,tools=BOKEH_TOOLS, toolbar_location='above',tooltips=[('Parameters', '@level_0 - @parameters'), ('Correlation', '@correlation')]) p.toolbar.autohide = True ## SETTING UP PLOT PROPERTIES p.grid.grid_line_color = None p.axis.axis_line_color = None p.axis.major_tick_line_color = None p.axis.major_label_text_font_size = "12pt" p.xaxis.major_label_orientation = pi/2 ## SETTING UP HEATMAP RECTANGLES cir = p.rect(x="level_0", y="parameters", width=1, height=1,source=source,fill_color={'field': 'correlation', 'transform': mapper},line_color=None) ## SETTING UP COLOR BAR color_bar = ColorBar(color_mapper=mapper, major_label_text_font_size="5pt",ticker=BasicTicker(desired_num_ticks=10),formatter=PrintfTickFormatter(format="%.1f"),label_standoff=6, border_line_color=None, location=(0, 0)) p.add_layout(color_bar, 'right') ## AVAILABLE COLOR SCHEMES COLOR_SCHEME = { 'Cividis':get_reversed_list(cividis(no_of_colors)), 'Gray':get_reversed_list(gray(no_of_colors)), 'Inferno':get_reversed_list(inferno(no_of_colors)), 'Magma':get_reversed_list(magma(no_of_colors)), 'Viridis':get_reversed_list(viridis(no_of_colors)), 'Turbo':get_reversed_list(turbo(no_of_colors)), } ## JS CALLBACK callback = CustomJS(args=dict(col_sch=COLOR_SCHEME,low=low_df_corr_min,high=high_df_corr_min,cir=cir,color_bar=color_bar), code=""" // JavaScript code goes here var chosen_color = cb_obj.value; var color_mapper = new Bokeh.LinearColorMapper({palette:col_sch[chosen_color], low:low, high:high}); cir.glyph.fill_color = {field: 'correlation', transform: color_mapper}; color_bar.color_mapper.low = low; color_bar.color_mapper.high = high; color_bar.color_mapper.palette = col_sch[chosen_color]; """) ## SELECT OPTION FOR INTERACTIVITY GIVEN TO USER select = Select(title='Color Palette',value='cividis', options=list(COLOR_SCHEME.keys()), width=200, height=50) ## CALL BACK TO BE TRIGGERED WHENEVER USER SELECTS A COLOR PALETTE select.js_on_change('value', callback) ## GENERATION FINAL PLOT BY BINDING PLOT AND SELECT OPTION final_plot = layout([[select],[p]]) curdoc().add_root(final_plot) output_file(path_to_save) save(final_plot) carry_bokeh_correction(path_to_save)
from numba import njit import scipy.misc from bokeh.io import curdoc from bokeh.layouts import column from bokeh.models import ColumnDataSource, Slider from bokeh.palettes import gray from bokeh.plotting import figure image = scipy.misc.ascent().astype(np.int32)[::-1, :] w, h = image.shape source = ColumnDataSource(data=dict(image=[image])) p = figure(x_range=(0, w), y_range=(0, h)) p.image('image', x=0, y=0, dw=w, dh=h, palette=gray(256), source=source) @njit def blur(outimage, image, amt): for i in range(amt, w-amt): for j in range(amt, h-amt): px = 0. for iw in range(-amt//2, amt//2): for jh in range(-amt//2, amt//2): px += image[i+iw, j+jh] outimage[i, j] = px/(amt*amt) def update(attr, old, new): out = image.copy() blur(out, image, 2*new + 1) source.data.update(image=[out])
def _process_series(self, series): self._init_cyclers() # clear figure. need to clear both the renderers as well as the # colorbars which are added to the right side. self._fig.renderers = [] self._fig.right = [] for i, s in enumerate(series): if s.is_2Dline: if s.is_parametric and self._use_cm: x, y, param = s.get_data() colormap = (next(self._cyccm) if self._use_cyclic_cm( param, s.is_complex) else next(self._cm)) ds, line, cb = self._create_gradient_line( x, y, param, colormap, s.label) self._fig.add_glyph(ds, line) if self.legend: self._handles[i] = cb self._fig.add_layout(cb, "right") else: if s.is_parametric: x, y, param = s.get_data() source = {"xs": x, "ys": y, "us": param} else: x, y = s.get_data() x, y, modified = self._detect_poles(x, y) if modified: self._fig.y_range.start = self.ylim[0] self._fig.y_range.end = self.ylim[1] source = {"xs": x, "ys": y} lkw = dict(line_width=2, legend_label=s.label, color=next(self._cl)) line_kw = self._kwargs.get("line_kw", dict()) if not s.is_point: self._fig.line("xs", "ys", source=source, **merge({}, lkw, line_kw)) else: self._fig.dot("xs", "ys", source=source, **merge({"size": 20}, lkw, line_kw)) elif s.is_contour and (not s.is_complex): x, y, z = s.get_data() x, y, zz = [t.flatten() for t in [x, y, z]] minx, miny, minz = min(x), min(y), min(zz) maxx, maxy, maxz = max(x), max(y), max(zz) contour_kw = self._kwargs.get("contour_kw", dict()).copy() cm = contour_kw.pop("palette", next(self._cm)) self._fig.image( image=[z], x=minx, y=miny, dw=abs(maxx - minx), dh=abs(maxy - miny), palette=cm, ) colormapper = LinearColorMapper(palette=cm, low=minz, high=maxz) cbkw = dict(width=8, title=s.label) colorbar = ColorBar(color_mapper=colormapper, **cbkw) self._fig.add_layout(colorbar, "right") self._handles[i] = colorbar elif s.is_implicit: points = s.get_data() # TODO: add color to the legend if len(points) == 2: # interval math plotting x, y, pixels = self._get_pixels(s, points[0]) x, y = x.flatten(), y.flatten() cm = ["#00000000", next(self._cl)] self._fig.image( image=[pixels], x=min(x), y=min(y), dw=abs(max(x) - min(x)), dh=abs(max(y) - min(y)), palette=cm, legend_label=s.label, ) else: x, y, z, ones, plot_type = points if plot_type == "contour": source = get_contour_data(x, y, z) lkw = dict( line_color=next(self._cl), line_width=2, source=source, legend_label=s.label, ) line_kw = self._kwargs.get("line_kw", dict()) self._fig.multi_line("xs", "ys", **merge({}, lkw, line_kw)) else: cm = ["#00000000", next(self._cl)] self._fig.image( image=[ones], x=min(x), y=min(y), dw=abs(max(x) - min(x)), dh=abs(max(y) - min(y)), palette=cm, legend_label=s.label, ) elif s.is_2Dvector: streamlines = self._kwargs.get("streamlines", False) if streamlines: x, y, u, v = s.get_data() sqk = dict(color=next(self._cl), line_width=2, line_alpha=0.8) stream_kw = self._kwargs.get("stream_kw", dict()) density = stream_kw.pop("density", 2) xs, ys = compute_streamlines(x[0, :], y[:, 0], u, v, density=density) self._fig.multi_line(xs, ys, **merge({}, sqk, stream_kw)) else: x, y, u, v = s.get_data() quiver_kw = self._kwargs.get("quiver_kw", dict()) data, quiver_kw = self._get_quivers_data( x, y, u, v, **quiver_kw) mag = data["magnitude"] color_mapper = LinearColorMapper(palette=next(self._cm), low=min(mag), high=max(mag)) # don't use color map if a scalar field is visible or if # use_cm=False solid = (True if ("scalar" not in self._kwargs.keys()) else (False if ((not self._kwargs["scalar"]) or (self._kwargs["scalar"] is None)) else True)) line_color = ({ "field": "magnitude", "transform": color_mapper } if ((not solid) and self._use_cm) else next(self._cl)) source = ColumnDataSource(data=data) # default quivers options qkw = dict(line_color=line_color, line_width=1, name=s.label) glyph = Segment(x0="x0", y0="y0", x1="x1", y1="y1", **merge({}, qkw, quiver_kw)) self._fig.add_glyph(source, glyph) if isinstance(line_color, dict): colorbar = ColorBar(color_mapper=color_mapper, width=8, title=s.label) self._fig.add_layout(colorbar, "right") self._handles[i] = colorbar elif s.is_complex and s.is_domain_coloring: x, y, magn_angle, img, colors = s.get_data() img = self._get_img(img) source = ColumnDataSource({ "image": [img], "abs": [magn_angle[:, :, 0]], "arg": [magn_angle[:, :, 1]], }) self._fig.image_rgba( source=source, x=x.min(), y=y.min(), dw=x.max() - x.min(), dh=y.max() - y.min(), ) if colors is not None: # chroma/phase-colorbar cm1 = LinearColorMapper(palette=[tuple(c) for c in colors], low=-self.pi, high=self.pi) ticks = [-self.pi, -self.pi / 2, 0, self.pi / 2, self.pi] labels = ["-π", "-π / 2", "0", "π / 2", "π"] colorbar1 = ColorBar( color_mapper=cm1, title="Argument", ticker=FixedTicker(ticks=ticks), major_label_overrides={ k: v for k, v in zip(ticks, labels) }, ) self._fig.add_layout(colorbar1, "right") if s.coloring == "f": # lightness/magnitude-colorbar cm2 = LinearColorMapper(palette=bp.gray(100), low=0, high=1) colorbar2 = ColorBar( color_mapper=cm2, title="Magnitude", ticker=FixedTicker(ticks=[0, 1]), major_label_overrides={ 0: "0", 1: "∞" }, ) self._fig.add_layout(colorbar2, "right") elif s.is_geometry: x, y = s.get_data() color = next(self._cl) pkw = dict(alpha=0.5, line_width=2, line_color=color, fill_color=color) patch_kw = self._kwargs.get("patch_kw", dict()) self._fig.patch(x, y, **merge({}, pkw, patch_kw)) else: raise NotImplementedError("{} is not supported by {}\n".format( type(s), type(self).__name__) + "Bokeh only supports 2D plots.") if len(self._fig.legend) > 0: self._fig.legend.visible = self.legend # interactive legend self._fig.legend.click_policy = "hide" self._fig.add_layout(self._fig.legend[0], "right")