def test_label_already_exists(self) -> None: legend = Legend(items=[LegendItem(label=field("foo"))]) renderer = GlyphRenderer() bpl._handle_legend_field("foo", legend, renderer) assert len(legend.items) == 1 assert legend.items[0].label == field("foo") assert legend.items[0].renderers == [renderer]
def test_LabelSet() -> None: label_set = LabelSet() assert label_set.level == 'annotation' assert label_set.x == field("x") assert label_set.y == field("y") assert label_set.x_units == 'data' assert label_set.y_units == 'data' assert label_set.text == field("text") assert label_set.angle == 0 assert label_set.angle_units == 'rad' assert label_set.x_offset == 0 assert label_set.y_offset == 0 assert label_set.render_mode == 'canvas' assert label_set.x_range_name == 'default' assert label_set.y_range_name == 'default' assert isinstance(label_set.source, ColumnDataSource) assert label_set.source.data == {} check_text_properties(label_set) check_fill_properties(label_set, "background_", None, 1.0) check_line_properties(label_set, "border_", None, 1.0, 1.0) check_properties_existence(label_set, [ "visible", "level", "x", "y", "x_units", "y_units", "text", "angle", "angle_units", "x_offset", "y_offset", "render_mode", "x_range_name", "y_range_name", "source" ], TEXT, ANGLE, prefix('border_', LINE), prefix('background_', FILL))
def test_Arrow() -> None: arrow = Arrow() assert arrow.x_start == field("x_start") assert arrow.y_start == field("y_start") assert arrow.start_units == 'data' assert arrow.start is None assert arrow.x_end == field("x_end") assert arrow.y_end == field("y_end") assert arrow.end_units == 'data' assert isinstance(arrow.end, ArrowHead) assert isinstance(arrow.source, ColumnDataSource) assert arrow.x_range_name == "default" assert arrow.y_range_name == "default" check_line_properties(arrow) check_properties_existence( arrow, ANNOTATION + [ "x_start", "y_start", "start_units", "start", "x_end", "y_end", "end_units", "end", "source", ], LINE)
def test_Whisker() -> None: whisker = Whisker() assert whisker.level == 'underlay' assert whisker.lower == field("lower") assert whisker.lower_units == 'data' assert isinstance(whisker.lower_head, ArrowHead) assert whisker.lower_head.size == 10 assert whisker.upper == field("upper") assert whisker.upper_units == 'data' assert isinstance(whisker.upper_head, ArrowHead) assert whisker.upper_head.size == 10 assert whisker.base == field("base") assert whisker.dimension == 'height' assert isinstance(whisker.source, ColumnDataSource) assert whisker.x_range_name == 'default' assert whisker.y_range_name == 'default' check_line_properties(whisker, "") check_properties_existence( whisker, ANNOTATION + [ "lower", "lower_units", "lower_head", "upper", "upper_units", "upper_head", "base", "base_units", "dimension", "source", ], LINE)
def test_Band() -> None: band = Band() assert band.level == 'annotation' assert band.lower == field("lower") assert band.lower_units == 'data' assert band.upper == field("upper") assert band.upper_units == 'data' assert band.base == field("base") assert band.dimension == 'height' assert isinstance(band.source, ColumnDataSource) assert band.x_range_name == 'default' assert band.y_range_name == 'default' check_line_properties(band, "", "#cccccc", 1.0, 0.3) check_fill_properties(band, "", "#fff9ba", 0.4) check_properties_existence( band, ANNOTATION + [ "lower", "lower_units", "upper", "upper_units", "base", "base_units", "dimension", "source", ], LINE, FILL)
def test_legend_powered_by_source(output_file_url, selenium, screenshot): plot = Plot(height=HEIGHT, width=WIDTH, x_range=Range1d(0, 4), y_range=Range1d(0, 4), toolbar_location=None) source = ColumnDataSource( dict( x=[1, 2, 3], y=[1, 2, 3], color=['red', 'green', 'blue'], label=['Color Red', 'Color Green', 'Color Blue'], )) circle = Circle(x='x', y='y', fill_color='color', size=20) circle_renderer = plot.add_glyph(source, circle) plot.add_layout( Legend(items=[ LegendItem(label=field('label'), renderers=[circle_renderer]) ])) # Save the plot and start the test save(plot) selenium.get(output_file_url) assert has_no_console_errors(selenium) # Take screenshot assert screenshot.is_valid()
def display_season_overview(src, seasonNum, yrange, xrange): # creating and displaying visualizations figure_season_overview = figure(title="Season Overview : "+str(seasonNum), tools="hover, save",\ y_range=yrange, x_range=list(xrange), plot_width=1200, plot_height=500) figure_season_overview.xaxis.major_label_orientation = 45 # Configuring figure_season_overview.yaxis.axis_label = 'Stadium Cities' # figure figure_season_overview.xaxis.axis_label = 'Dates' # settings rect = Rect(x="dates", y="cities", width=0.8, height=0.8, fill_alpha=0.8, fill_color="type_color") rect_render = figure_season_overview.add_glyph(src, rect) legend = Legend(items=[ LegendItem(label=field("label"), renderers=[rect_render]) ]) figure_season_overview.add_layout(legend, 'left') figure_season_overview.legend.background_fill_color = "grey" figure_season_overview.legend.background_fill_alpha = 0.1 figure_season_overview.legend.border_line_color = "black" figure_season_overview.select_one(HoverTool).tooltips = [ ("Date", "@dates"), ("Team1", "@team1"), # Configuring ("Team2", "@team2"), # Hover ("Venue", "@venues"), # Tool ("City", "@cities"), ("Winner", "@winners"), ("Man of the match","@player_of_match") ] return figure_season_overview # displaying generated visualization
def jitter(field_name, width, mean=0, distribution="uniform", range=None): ''' Create a ``DataSpec`` dict to apply a client-side ``Jitter`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with width (float) : the width of the random distribition to apply mean (float, optional) : an offset to apply (default: 0) distribution (str, optional) : ``"uniform"`` or ``"normal"`` (default: ``"uniform"``) range (Range, optional) : a range to use for computing synthetic coordinates when necessary, e.g. a ``FactorRange`` when the column data is categorical (default: None) Returns: dict ''' return field( field_name, Jitter(mean=mean, width=width, distribution=distribution, range=range))
def factor_cmap(field_name, palette, factors, start=0, end=None, nan_color="gray"): ''' Create a ``DataSpec`` dict to apply a client-side ``CategoricalColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with palette (seq[color]) : a list of colors to use for colormapping factors (seq) : a sequences of categorical factors corresponding to the palette start (int, optional) : a start slice index to apply when the column data has factors with multiple levels. (default: 0) end (int, optional) : an end slice index to apply when the column data has factors with multiple levels. (default: None) nan_color (color, optional) : a default color to use when mapping data from a column does not succeed (default: "gray") Returns: dict ''' return field(field_name, CategoricalColorMapper(palette=palette, factors=factors, start=start, end=end, nan_color=nan_color))
def jitter(field_name, width, mean=0, distribution="uniform", range=None): ''' Create a ``DataSpec`` dict to apply a client-side ``Jitter`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with width (float) : the width of the random distribition to apply mean (float, optional) : an offset to apply (default: 0) distribution (str, optional) : ``"uniform"`` or ``"normal"`` (default: ``"uniform"``) range (Range, optional) : a range to use for computing synthetic coordinates when necessary, e.g. a ``FactorRange`` when the column data is categorical (default: None) Returns: dict ''' return field(field_name, Jitter(mean=mean, width=width, distribution=distribution, range=range))
def log_cmap(field_name, palette, low, high, low_color=None, high_color=None, nan_color="gray"): ''' Create a ``DataSpec`` dict to apply a client-side ``LogColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with palette (seq[color]) : a list of colors to use for colormapping low (float) : a minimum value of the range to map into the palette. Values below this are clamped to ``low``. high (float) : a maximum value of the range to map into the palette. Values above this are clamped to ``high``. low_color (color, optional) : color to be used if data is lower than ``low`` value. If None, values lower than ``low`` are mapped to the first color in the palette. (default: None) high_color (color, optional) : color to be used if data is higher than ``high`` value. If None, values higher than ``high`` are mapped to the last color in the palette. (default: None) nan_color (color, optional) : a default color to use when mapping data from a column does not succeed (default: "gray") ''' return field(field_name, LogColorMapper(palette=palette, low=low, high=high, nan_color=nan_color, low_color=low_color, high_color=high_color))
def test_legend_item_with_field_label_raises_error_if_field_not_in_cds(): legend_item = LegendItem() gr_1 = GlyphRenderer(data_source=ColumnDataSource()) legend_item.label = field('label') legend_item.renderers = [gr_1] with mock.patch('bokeh.core.validation.check.logger') as mock_logger: check_integrity([legend_item]) assert mock_logger.error.call_count == 1
def test_handle_node_marker_dataspec_correctly(self) -> None: node_source = {'marker': ['square', 'circle', 'x']} kw = bpg.get_graph_kwargs(node_source, {}, node_marker='marker') node_glyph = kw['node_renderer'].glyph assert isinstance(node_glyph, Scatter) assert node_glyph.marker == field('marker')
def test_legend_item_with_field_label_and_different_data_sources_raises_a_validation_error(): legend_item = LegendItem() gr_1 = GlyphRenderer(data_source=ColumnDataSource(data={'label': [1]})) gr_2 = GlyphRenderer(data_source=ColumnDataSource(data={'label': [1]})) legend_item.label = field('label') legend_item.renderers = [gr_1, gr_2] with mock.patch('bokeh.core.validation.check.logger') as mock_logger: check_integrity([legend_item]) assert mock_logger.error.call_count == 1
def transform(field_name, transform): ''' Create a ``DataSpec`` dict to apply an arbitrary client-side ``Transform`` to a ``ColumnDataSource`` column. Args: field_name (str) : A field name to configure ``DataSpec`` with transform (Transform) : A transforms to apply to that field Returns: dict ''' return field(field_name, transform)
def dodge(field_name, value, range=None): ''' Create a ``DataSpec`` dict to apply a client-side ``Jitter`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with value (float) : the fixed offset to add to column data range (Range, optional) : a range to use for computing synthetic coordinates when necessary, e.g. a ``FactorRange`` when the column data is categorical (default: None) Returns: dict ''' return field(field_name, Dodge(value=value, range=range))
def log_cmap(field_name, palette, low, high, low_color=None, high_color=None, nan_color="gray"): ''' Create a ``DataSpec`` dict to apply a client-side ``LogColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with palette (seq[color]) : a list of colors to use for colormapping low (float) : a minimum value of the range to map into the palette. Values below this are clamped to ``low``. high (float) : a maximum value of the range to map into the palette. Values above this are clamped to ``high``. low_color (color, optional) : color to be used if data is lower than ``low`` value. If None, values lower than ``low`` are mapped to the first color in the palette. (default: None) high_color (color, optional) : color to be used if data is higher than ``high`` value. If None, values higher than ``high`` are mapped to the last color in the palette. (default: None) nan_color (color, optional) : a default color to use when mapping data from a column does not succeed (default: "gray") ''' return field( field_name, LogColorMapper(palette=palette, low=low, high=high, nan_color=nan_color, low_color=low_color, high_color=high_color))
def factor_cmap(field_name, palette, factors, start=0, end=None, nan_color="gray"): ''' Create a ``DataSpec`` dict to apply a client-side ``CategoricalColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with palette (seq[color]) : a list of colors to use for colormapping factors (seq) : a sequences of categorical factors corresponding to the palette start (int, optional) : a start slice index to apply when the column data has factors with multiple levels. (default: 0) end (int, optional) : an end slice index to apply when the column data has factors with multiple levels. (default: None) nan_color (color, optional) : a default color to use when mapping data from a column does not succeed (default: "gray") Returns: dict ''' return field( field_name, CategoricalColorMapper(palette=palette, factors=factors, start=start, end=end, nan_color=nan_color))
def test_legend_powered_by_source(output_file_url, selenium, screenshot): plot = Plot( height=HEIGHT, width=WIDTH, x_range=Range1d(0, 4), y_range=Range1d(0, 4), toolbar_location=None ) source = ColumnDataSource(dict( x=[1, 2, 3], y=[1, 2, 3], color=['red', 'green', 'blue'], label=['Color Red', 'Color Green', 'Color Blue'], )) circle = Circle(x='x', y='y', fill_color='color', size=20) circle_renderer = plot.add_glyph(source, circle) plot.add_layout(Legend(items=[LegendItem(label=field('label'), renderers=[circle_renderer])])) # Save the plot and start the test save(plot) selenium.get(output_file_url) assert has_no_console_errors(selenium) # Take screenshot assert screenshot.is_valid()
) circles = plot.circle( x='fpl_orbper', y='fpl_rade', size='circlesize', source=source, fill_color={ 'field': 'category', 'transform': color_mapper }, fill_alpha=0.8, line_color='#000000', line_width=0.5, line_alpha=0.5, legend=field('category'), ) circles_solsys = plot.circle( x='periods', y='radii', size='circlesize', source=source_solsys, fill_color='#ffffff', line_color='#000000', line_width=0.5, line_alpha=0.5, ) plot.add_tools( HoverTool(tooltips="@fpl_name",
def test__find_legend_item() -> None: legend = Legend(items=[LegendItem(label=value("foo")), LegendItem(label=field("bar"))]) assert bpl._find_legend_item(value("baz"), legend) is None assert bpl._find_legend_item(value("foo"), legend) is legend.items[0] assert bpl._find_legend_item(field("bar"), legend) is legend.items[1]
color_mapper = CategoricalColorMapper(palette=Spectral4, factors=group_list) plot.circle( x='gross', y='open_week', size='count', source=source, fill_color={ 'field': 'Quality', 'transform': color_mapper }, fill_alpha=0.8, line_color='#7c7e71', line_width=0.5, line_alpha=0.5, legend=field('Quality'), ) #plot.add_tools(HoverTool(tooltips="@Country", show_arrow=False, point_policy='follow_mouse')) def animate_update(): month = slider.value + 1 if month > months[-1]: month = months[0] slider.value = month def slider_update(attrname, old, new): month = slider.value label.text = str(month) source.data = data[month]
x = np.ones(1000) y = np.random.random(1000) * 10 source = ColumnDataSource(data=dict(x=x, xn=2 * x, xu=3 * x, y=y)) normal = Jitter(width=0.2, distribution="normal") uniform = Jitter(width=0.2, distribution="uniform") p = figure(x_range=(0, 4), y_range=(0, 10), toolbar_location=None, x_axis_location="above") p.circle(x='x', y='y', color='firebrick', source=source, size=5, alpha=0.5) r1 = p.circle(x='xn', y='y', color='olive', source=source, size=5, alpha=0.5) n1 = p.circle(x=field('xn', normal), y='y', color='olive', source=source, size=5, alpha=0.5, visible=False) r2 = p.circle(x='xu', y='y', color='navy', source=source, size=5, alpha=0.5) u2 = p.circle(x=field('xu', uniform), y='y', color='navy', source=source, size=5, alpha=0.5, visible=False)
title="US unemployment January 2021 (by state)", width=1000, height=600, x_axis_location=None, y_axis_location=None, tools="pan,wheel_zoom,reset", ) p.grid.grid_line_color = None color_mapper = LinearColorMapper(palette=Viridis11) r = p.patches( state_xs, state_ys, line_color="white", hover_line_color="black", fill_color=field("rate", color_mapper), ) r.data_source.data["code"] = [code for code in states] r.data_source.data["rate"] = [january_2021[code] for code in states] HI_i = list(states.keys()).index("HI") AK_i = list(states.keys()).index("AK") filter = ~IndexFilter(indices=[HI_i, AK_i]) r.view.filter &= filter p.add_tools( HoverTool( tooltips=[("state", "@code"), ("rate", "@rate{0.0}%")], renderers=[r],
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
color_mapper = CategoricalColorMapper(palette=bokeh.palettes.viridis(6), factors=type) plot.circle( x='Cumulative Cases', y='New Confirmed Cases (Past Week)', size=36, source=source, fill_color={ 'field': 'Infection Source', 'transform': color_mapper }, fill_alpha=1.0, line_color='#7c7e71', line_width=0.5, line_alpha=0.5, legend=field('Infection Source'), ) plot.legend.location = "top_left" plot.title.text_font_size = "25px" plot.add_tools( HoverTool(tooltips=[("Infection Source", "@{Infection Source}"), ("Cum Cases", "@{Cumulative Cases}"), ("New Cases", "@{New Confirmed Cases (Past Week)}")], show_arrow=False, point_policy='follow_mouse')) def animate_update(): day = slider.value + 1 if day > days[-1]: day = days[0]
plot.add_glyph(text_source, text) # Add the circle color_mapper = CategoricalColorMapper(palette=Spectral6, factors=regions_list) renderer_source = sources['_%s' % years[0]] circle_glyph = Circle( x='fertility', y='life', size='population', fill_color={'field': 'region', 'transform': color_mapper}, fill_alpha=0.8, line_color='#7c7e71', line_width=0.5, line_alpha=0.5) circle_renderer = plot.add_glyph(renderer_source, circle_glyph) # Add the hover (only against the circle and not other plot elements) tooltips = "@index" plot.add_tools(HoverTool(tooltips=tooltips, renderers=[circle_renderer])) plot.add_layout(Legend(items=[LegendItem(label=field('region'), renderers=[circle_renderer])])) # Add the slider code = """ var year = slider.value, sources = %s, new_source_data = sources[year].data; renderer_source.data = new_source_data; text_source.data = {'year': [String(year)]}; """ % js_source_array callback = CustomJS(args=sources, code=code) slider = Slider(start=years[0], end=years[-1], value=1, step=1, title="Year", callback=callback, name='testy') callback.args["renderer_source"] = renderer_source callback.args["slider"] = slider callback.args["text_source"] = text_source
# create figure p = figure(title='Decision Surface (double tap to add data)', tools=[], width=700, height=700, x_range=state.xlim, y_range=state.ylim) p.background_fill_color = 'white' p.xaxis.axis_label = 'X' p.yaxis.axis_label = 'Y' p.circle(source=source, x='x', y='y', color='color', alpha=1, legend=field('level')) p.square(source=surface, x='x', y='y', color='color', alpha=.1, size=5.4, legend=field('level')) # create buttons and add callbacks # reset data button_reset = Button(label='Reset', button_type='primary') button_reset.on_click(lambda: callbacks.callback_button_reset(source, surface)) # add data on double tap p.on_event(
def create_team(season1,season2): teamDF = (sql.read.format("com.databricks.spark.csv").\ option("header","true").load(data_opath + "dreamTeam" + season1+"_"+season2+".csv")) yaxis = [str(x) for x in range(1, 7)] xaxis = ["a","b"] player=[str(i.name) for i in teamDF.collect()] batsman_overall=[int(i.batsmanrating) for i in teamDF.collect()] bowler_overall=[int(i.bowlerrating) for i in teamDF.collect()] fielder_overall=[int(i.fielderrating) for i in teamDF.collect()] strikerate=[float(i.strikerate) for i in teamDF.collect()] economyrate=[float(i.economyrate) for i in teamDF.collect()] ycoordinate =["Batsman","Batsman","Batsman","Batsman","Batsman",\ "Batsman","Bowler","Bowler","Bowler","Bowler","Bowler"] colormap = { "Batsman" : "#0092CD", "Bowler" : "#4FC730", } source = ColumnDataSource( data=dict( role = [i for i in ycoordinate], xpoints = ["a","a","a","a","a","a","b","b","b","b","b"], ypoints = [2,3,4,5,6,1,6,5,4,3,2], player = [i for i in player], batscore = [i for i in batsman_overall], bowlscore = [i if i != 0 else 2 for i in bowler_overall], fieldscore = [i for i in fielder_overall], srate = [i if i!= 100.0 else "NA" for i in strikerate], erate = [i if i!= 100.0 else "NA" for i in economyrate], type_color = [colormap[x] for x in ycoordinate], ) ) p = figure(title = "Dream Team", x_range = xaxis, y_range = list(reversed(yaxis)), tools ="hover") p.plot_width = 800 p.plot_height = 500 p.toolbar_location = None p.outline_line_color = None p.axis.visible = False rect = Rect(x="xpoints", y="ypoints", width=0.9, height=0.9, fill_color="type_color") rect_render = p.add_glyph(source, rect) legend = Legend(items=[LegendItem(label=field("role"), renderers=[rect_render])]) p.add_layout(legend, 'right') text_props = { "source": source, "angle": 0, "color": "black", "text_align": "center", "text_baseline": "middle", } p.text(x="xpoints", y="ypoints", text="player", text_font_style="bold", text_font_size="12pt", **text_props) p.grid.grid_line_color = None p.select_one(HoverTool).tooltips = [ ("player","@player"), ("role","@role"), ("batting","@batscore"), ("bowling","@bowlscore"), ("fielding","@fieldscore"), ("strikerate","@srate"), ("economyrate","@erate") ] return p
from bokeh.io import save from bokeh.core.properties import field from bokeh.models import ColumnDataSource, Plot, Circle, Legend, LegendItem, Range1d plot = Plot( width=600, height=600, x_range=Range1d(0, 4), y_range=Range1d(0, 4), toolbar_location=None, ) source = ColumnDataSource( dict( x=[1, 2, 3], y=[1, 2, 3], color=['red', 'green', 'blue'], label=['Color Red', 'Color Green', 'Color Blue'], )) circle = Circle(x='x', y='y', fill_color='color', size=20) circle_renderer = plot.add_glyph(source, circle) plot.add_layout( Legend( items=[LegendItem(label=field('label'), renderers=[circle_renderer])])) save(plot)
color_mapper = CategoricalColorMapper(palette=Spectral10, factors=list(df.Name.unique())) plot.quad( top='Upper_bound', bottom='Lower_bound', left='Left_bound', right='Right_bound', source=source, fill_color={'field': 'Name', 'transform': color_mapper}, fill_alpha=0.2, line_color='#7c7e71', line_width=0.5, line_alpha=0.5, legend=field('Name'), ) plot.text( x='X_coord', y='Upper_bound', text='Upper_bound', source=source, ) plot.square( x='X_coord', y='Average_Rewards', size=10, source=source, fill_color={'field': 'Name', 'transform': color_mapper}, fill_alpha=0.8,
label = Label(x=1.1, y=18, text=str(years[0]), text_font_size='70pt', text_color='#eeeeee') plot.add_layout(label) color_mapper = CategoricalColorMapper(palette=Spectral6, factors=regions_list) plot.circle( x='fertility', y='life', size='population', source=source, fill_color={'field': 'region', 'transform': color_mapper}, fill_alpha=0.8, line_color='#7c7e71', line_width=0.5, line_alpha=0.5, legend=field('region'), ) plot.add_tools(HoverTool(tooltips="@index", show_arrow=False, point_policy='follow_mouse')) def animate_update(): year = slider.value + 1 if year > years[-1]: year = years[0] slider.value = year def slider_update(attrname, old, new): year = slider.value label.text = str(year) source.data = sources[year].data
def createGapMinder(pds, features, curdoc): """Generates a gap minder plot. :param pds: list of dicitionaries. :param features: the list of features :param curdoc: The curdoc instance :returns: The gapminder plot and a slider :rtype: bokeh.layouts.row, bokeh.models.Slider """ mysource = ColumnDataSource(data=pds[0]) myplot = figure(x_range=(0, 10), y_range=(0, 10), title='Word Frequencies with Ratings', plot_height=300) myplot.xgrid.grid_line_color = None myplot.ygrid.grid_line_color = None myplot.toolbar.logo = None myplot.toolbar_location = None myplot.xaxis.axis_label = "Hover on Circles to see the words" color_mapper = CategoricalColorMapper(palette=['red','blue',"green","yellow","black"], factors=["1","2","3","4","5"]) myplot.circle( x="xval", y="yval", size="freq", source=mysource, fill_color={'field': 'sentiment', 'transform': color_mapper}, fill_alpha=0.8, line_color='#7c7e71', line_width=0.5, line_alpha=0.2, legend=field('sentiment') ) myplot.add_tools(HoverTool(tooltips="@word", show_arrow=False, point_policy='follow_mouse')) myslider = Slider(start=0, end=2, value=0, step=1, title=features[0]) mybutton = Button(label='Play', width=60) def animate(): """The slider animate function :returns: nothing :rtype: None """ global callback_id if mybutton.label == 'Play' : mybutton.label = 'Pause' callback_id = curdoc.add_periodic_callback(animate_update, 1000) else: mybutton.label = 'Play' curdoc.remove_periodic_callback(callback_id) def slider_update(attrname, old, new): """The slider update function """ val = myslider.value myslider.title = features[val] mysource.data = pds[val] def animate_update(): val = myslider.value + 1 if val > 2: val = 0 myslider.value = val myslider.on_change('value', slider_update) mybutton.on_click(animate) inputs = widgetbox(myslider,mybutton) r = row(myplot,inputs) # layout = layout([[myplot], [myslider, mybutton]], sizing_mode='fixed') return r, myslider
label = Label(x=1.1, y=18, text=str(years[0]), text_font_size='70pt', text_color='#eeeeee') plot.add_layout(label) color_mapper = CategoricalColorMapper(palette=Spectral6, factors=regions_list) plot.circle( x='fertility', y='life', size='population', source=source, fill_color={'field': 'region', 'transform': color_mapper}, fill_alpha=0.8, line_color='#7c7e71', line_width=0.5, line_alpha=0.5, legend=field('region'), ) plot.add_tools(HoverTool(tooltips="@Country", show_arrow=False, point_policy='follow_mouse')) def animate_update(): year = slider.value + 1 if year > years[-1]: year = years[0] slider.value = year def slider_update(attrname, old, new): year = slider.value label.text = str(year) source.data = data[year]
def drawInteractiveNW(df, nw=None, edgesdf=None, color_attr="Cluster", label_attr="name", title="Interactive Network Visualization", plotfile=None, inline=False): def buildNetworkX(linksdf, id1='Source', id2='Target', directed=False): linkdata = [(getattr(link, id1), getattr(link, id2)) for link in linksdf.itertuples()] g = nx.DiGraph() if directed else nx.Graph() g.add_edges_from(linkdata) return g if inline: output_notebook() if plotfile: output_file(plotfile+".html") if nw is None: if edgesdf is None: print("Must specify either network or edges DataFrame") return nw = buildNetworkX(edgesdf) node_colors, edge_colors, attr_colors = dn.getCategoricalColors(nw, df, color_attr, None, True, None) xmin = df['x'].min() xmax = df['x'].max() ymin = df['y'].min() ymax = df['y'].max() rng = max((xmax-xmin), (ymax-ymin)) nNodes = len(df) size = 4*rng/math.sqrt(nNodes) node_indices = list(range(nNodes)) tooltips=[ (label_attr, "@"+label_attr), (color_attr, "@"+color_attr) ] plot = figure(title=title, plot_width=800, plot_height=800, x_range=(xmin-size, xmax+size), y_range=(ymin-size, ymax+size), tools="pan,wheel_zoom,box_zoom,reset", toolbar_location="right", output_backend="webgl") plot.add_tools(HoverTool(tooltips=tooltips), TapTool(), BoxSelectTool()) graph = GraphRenderer() # set node renderer and data graph.node_renderer.glyph = Circle(size=size, fill_color="fill_color", line_color='gray') graph.node_renderer.selection_glyph = Circle(size=size, fill_color="fill_color", line_color='black', line_width=2) graph.node_renderer.hover_glyph = Circle(size=size, fill_color="fill_color", line_color='black') graph.node_renderer.data_source.data = {'index': node_indices, label_attr: df[label_attr].tolist(), 'fill_color': node_colors, color_attr: df[color_attr].fillna('').tolist(), 'x': df['x'].tolist(), 'y': df['y'].tolist(), } # set edge renderer and data graph.edge_renderer.glyph = MultiLine(line_color="line_color", line_width=1) graph.edge_renderer.data_source.data = {'start': [e[0] for e in nw.edges], 'end': [e[1] for e in nw.edges], 'line_color': edge_colors } # set layout graph_layout = dict(zip(node_indices, zip(df['x'], df['y']))) graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout) # set legend by adding dummy glyph with legend plot.circle( x='x', y='y', radius=0.0, color='fill_color', legend=field(color_attr), source=graph.node_renderer.data_source.data) plot.legend.location = "top_left" plot.legend.padding = 0 plot.legend.margin = 0 graph.selection_policy = NodesAndLinkedEdges() # hide axes and grids plot.xaxis.visible = False plot.yaxis.visible = False plot.xgrid.visible = False plot.ygrid.visible = False plot.renderers.append(graph) show(plot)