def test_get_svgs_with_svg_present(webdriver): def fix_ids(svg): svg = re.sub(r'id="\w{12}"', 'id="X"', svg) svg = re.sub(r'url\(#\w{12}\)', 'url(#X)', svg) return svg layout = Plot(x_range=Range1d(), y_range=Range1d(), plot_height=20, plot_width=20, toolbar_location=None, outline_line_color=None, border_fill_color=None, background_fill_color="red", output_backend="svg") svg0 = fix_ids(bie.get_svgs(layout, driver=webdriver)[0]) svg1 = fix_ids(bie.get_svgs(layout, driver=webdriver)[0]) svg2 = ( '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ' 'width="20" height="20" style="width: 20px; height: 20px;">' '<defs/>' '<g>' '<g transform="scale(1,1) translate(0.5,0.5)">' '<rect fill="#FFFFFF" stroke="none" x="0" y="0" width="20" height="20"/>' '<rect fill="red" stroke="none" x="5" y="5" width="10" height="10"/>' '<g/>' '</g>' '</g>' '</svg>') assert svg0 == svg2 assert svg1 == svg2
def histogram_plot(states, height, width, data_top, data_source, n_ticks, n_minor_ticks=0, fill_color=None): '''Create a bokeh histogram using quad shapes''' from bokeh.plotting import Figure # Create histogram object hist_obj = Figure(plot_height=height, plot_width=width, title="", toolbar_location=None) # Data top is string of var name from data_source fill_color = '#f0f5f5' if fill_color == None else fill_color hist_obj.quad(top=data_top, bottom=0, source=data_source, left="left", right="right", fill_color=fill_color, line_color='black') # set number of major and minor ticks hist_obj.xaxis[0].ticker.desired_num_ticks = n_ticks hist_obj.xaxis[0].ticker.num_minor_ticks = n_minor_ticks hist_obj.y_range = Range1d(0, 1) hist_obj.x_range = Range1d(states[0] - 0.5, states[-1] + 0.5) return hist_obj
def zooming_in(self): ctrl = self.roi_controller roi_bb = self.roi_model.bounding_box(margin=.1)[self.first_active_roi] xlim = roi_bb[[0, 2]].tolist() ylim = roi_bb[[1, 3]].tolist() xlim, ylim = match_aspect(xlim, ylim) zooming_in_fig = figure(**self.zooming_in_figure_kwargs) zooming_in_fig.add_tools(BoxZoomTool(match_aspect=True)) if self.global_map_values is not None: scalar_map_2d(self.global_map_cells, self.global_map_values, figure=zooming_in_fig, **self.scalar_map_2d_kwargs) else: for cells, values in zip(self.roi_tessellations, self.roi_map_values): scalar_map_2d(cells, values, figure=zooming_in_fig, **self.scalar_map_2d_kwargs) traj_handles = plot_trajectories(self.points, figure=zooming_in_fig, **self.trajectories_kwargs) self.trajectory_handles = traj_handles[0::2] self.location_handles = traj_handles[1::2] zooming_in_fig.x_range = Range1d(*xlim) zooming_in_fig.y_range = Range1d(*ylim) self.roi_view_zooming_in = zooming_in_fig return zooming_in_fig
def network_dynamic(self, df): graph = nx.from_pandas_edgelist(df, 'word1', 'word2', 'count') # Establish which categories will appear when hovering over each node HOVER_TOOLTIPS = [("", "@index")] # Create a plot — set dimensions, toolbar, and title plot = figure(tooltips=HOVER_TOOLTIPS, tools="pan,wheel_zoom,save,reset", active_scroll='wheel_zoom', x_range=Range1d(-10.1, 10.1), y_range=Range1d(-10.1, 10.1), plot_width=1000, title='') # Create a network graph object with spring layout network_graph = from_networkx(graph, nx.spring_layout, scale=10, center=(0, 0)) # Set node size and color network_graph.node_renderer.glyph = Circle(size=15, fill_color='skyblue') # Set edge opacity and width network_graph.edge_renderer.glyph = MultiLine(line_alpha=0.5, line_width=1) #Add network graph to the plot plot.renderers.append(network_graph) script, div = components(plot) return script, div
def test_bad_extra_range_name(self): p = figure() p.xaxis.x_range_name = "junk" with mock.patch('bokeh.core.validation.check.log') as mock_logger: check_integrity([p]) assert mock_logger.error.call_count == 1 assert mock_logger.error.call_args[0][0].startswith( "E-1020 (BAD_EXTRA_RANGE_NAME): An extra range name is configued with a name that does not correspond to any range: x_range_name='junk' [LinearAxis" ) p = figure() p.extra_x_ranges['foo'] = Range1d() p.grid.x_range_name = "junk" with mock.patch('bokeh.core.validation.check.log') as mock_logger: check_integrity([p]) assert mock_logger.error.call_count == 1 assert mock_logger.error.call_args[0][0].startswith( "E-1020 (BAD_EXTRA_RANGE_NAME): An extra range name is configued with a name that does not correspond to any range: x_range_name='junk' [Grid" ) assert mock_logger.error.call_args[0][0].count("Grid") == 2 # test whether adding a figure (*and* it's extra ranges) # to another's references doesn't create a false positive p, dep = figure(), figure() dep.extra_x_ranges['foo'] = Range1d() dep.grid.x_range_name = "foo" p.x_range.callback = CustomJS(code="", args={"dep": dep}) assert dep in p.references() with mock.patch('bokeh.core.validation.check.log') as mock_logger: check_integrity([p]) assert mock_logger.error.call_count == 0
def test_layout_html_on_parent_first(): p = Plot(x_range=Range1d(), y_range=Range1d()) layout = row(p) bie.get_layout_html(layout) bie.get_layout_html(p, height=100, width=100)
def add_graph_glyphs(): p.x_range = Range1d(-1, graph_array.shape[0]) p.y_range = Range1d(graph_array.shape[1], -1) circles = { n: points_on_a_circle(n=n, radius=0.4) for n in range(1, max_nodes + 1) } all_circles = [] all_xs = [] all_ys = [] for i, g in numpy.ndenumerate(graph_array): if g: xs = [] ys = [] c = circles[g.number_of_nodes()] + numpy.array(i) all_circles.append(c) try: for e1, e2 in g.edges_iter(): xs.append([c[e1][0], c[e2][0]]) ys.append([c[e1][1], c[e2][1]]) except IndexError: print(g.name) all_xs += xs all_ys += ys circle_xys = numpy.concatenate(all_circles) p.circle(x=circle_xys[:, 0], y=circle_xys[:, 1], radius=0.02) p.multi_line(xs=all_xs, ys=all_ys) return
def get_plot(source, plot_width=800, plot_height=200, x_range=None): plot = figure( plot_width=plot_width, plot_height=plot_height, toolbar_location=None, tools="pan,box_select,hover,wheel_zoom,box_zoom,tap,reset", active_scroll="wheel_zoom", x_axis_type='datetime' ) x_col_name = 'time' y_col_name = 'active' xs = source.data[x_col_name] ys = source.data[y_col_name] plot.circle( source=source, x=x_col_name, y=y_col_name ) plot.min_border = 30 if x_range: plot.x_range = x_range else: plot.x_range = Range1d(start=min(xs) - 1, end=max(xs) + 1) try: plot.y_range = Range1d(start=min(ys) - 1, end=max(ys) + 1) except TypeError: pass return gridplot( [[plot]], toolbar_options=dict(logo='grey') )
def line( self, df=None, x: str = None, y=None, color: str = None, text: str = None, color_order: list = None, ): p = self._chart.figure data = df.copy() if data[x].dtype == object: data[x] = pd.to_datetime(data[x]) p.xaxis.formatter = self.tick_formater('datetime') N = 30 p.x_range = Range1d(data[x].min() - pd.Timedelta(days=0.1 * N), data[x].max() + pd.Timedelta(days=0.1 * N)) p.y_range = Range1d(data[y].min(), data[y].max()) if data[y].dtype == np.int64: p.yaxis.formatter = self.tick_formater('integer') elif data[y].dtype == np.float64: p.yaxis.formatter = self.tick_formater('float') if isinstance(y, str): if color is not None: data = pd.pivot_table(data, index=x, columns=color, values=y).reset_index() #text_data = pd.pivot_table(data, index=x, columns=color, values=text).reset_index() y = df[color].unique() #text = df[color].unique() else: y = [y] #text = [text] #data = data.merge(text_data) elif isinstance(y, list): if color is None: color = y else: if not isinstance(color, list) or set(color) != set(y): raise Exception("Wrong set of y and color") if color_order is not None: y = color_order for sy in y: p.line(data[x], data[sy], line_width=2, line_color=self.next_color(), legend_label=sy) if color: p.legend.title = color p.legend.location = "top_left" p.yaxis.visible = True #print(p.yaxis.__dict__()) print(p.y_range.start) return self
def test_axis_type_auto(self): assert(bph._get_axis_class("auto", FactorRange(), 0)) == (CategoricalAxis, {}) assert(bph._get_axis_class("auto", FactorRange(), 1)) == (CategoricalAxis, {}) assert(bph._get_axis_class("auto", DataRange1d(), 0)) == (LinearAxis, {}) assert(bph._get_axis_class("auto", DataRange1d(), 1)) == (LinearAxis, {}) assert(bph._get_axis_class("auto", Range1d(), 0)) == (LinearAxis, {}) assert(bph._get_axis_class("auto", Range1d(), 1)) == (LinearAxis, {}) assert(bph._get_axis_class("auto", Range1d(start=datetime.datetime(2018, 3, 21)), 0)) == (DatetimeAxis, {}) assert(bph._get_axis_class("auto", Range1d(start=datetime.datetime(2018, 3, 21)), 1)) == (DatetimeAxis, {})
def test__get_scale_numeric_range_linear_axis(): s = bph._get_scale(Range1d(), "linear") assert isinstance(s, LinearScale) s = bph._get_scale(Range1d(), "datetime") assert isinstance(s, LinearScale) s = bph._get_scale(Range1d(), "auto") assert isinstance(s, LinearScale)
def test_save_layout_html_resets_plot_dims(): initial_height, initial_width = 200, 250 layout = Plot(x_range=Range1d(), y_range=Range1d(), plot_height=initial_height, plot_width=initial_width) bie.save_layout_html(layout, height=100, width=100) assert layout.plot_height == initial_height assert layout.plot_width == initial_width
def test_get_svgs_no_svg_present(): layout = Plot(x_range=Range1d(), y_range=Range1d(), plot_height=20, plot_width=20, toolbar_location=None) svgs = bie.get_svgs(layout) assert svgs == []
def test_get_screenshot_as_png(): layout = Plot(x_range=Range1d(), y_range=Range1d(), plot_height=20, plot_width=20, toolbar_location=None, outline_line_color=None, background_fill_color=None, border_fill_color=None) png = bie.get_screenshot_as_png(layout) assert png.size == (20, 20) # a 20x20px image of transparent pixels assert png.tobytes() == ("\x00"*1600).encode()
def test_get_svgs_with_svg_present(): layout = Plot(x_range=Range1d(), y_range=Range1d(), plot_height=20, plot_width=20, toolbar_location=None, outline_line_color=None, border_fill_color=None, background_fill_color="red", output_backend="svg") svgs = bie.get_svgs(layout) assert svgs[0] == ('<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ' 'width="20" height="20" style="width: 20px; height: 20px;"><defs/><g><g transform="scale(1,1) ' 'translate(0.5,0.5)"><rect fill="#FFFFFF" stroke="none" x="0" y="0" width="20" height="20"/>' '<rect fill="red" stroke="none" x="5" y="5" width="10" height="10"/><g/><g/><g/><g/></g></g></svg>')
def make_base_figure(iterations): """ Create the base plot with a horizontal "good value" band of height 60 in the middle. """ figure = bokeh_plt.figure(tools="pan,box_zoom,reset,save", y_axis_label="output", x_axis_label="iteration", y_range=Range1d(0, 100), x_range=Range1d(0, iterations)) figure.rect(50, 50, iterations, 80 - 20, color="green", fill_alpha=0.1) return figure
def test_save_layout_html_resets_plot_dims(): initial_height, initial_width = 200, 250 layout = Plot(x_range=Range1d(), y_range=Range1d(), plot_height=initial_height, plot_width=initial_width) with NamedTemporaryFile() as tmp: bie.save_layout_html(layout, tmp.name, height=100, width=100) assert layout.plot_height == initial_height assert layout.plot_width == initial_width
def test_get_screenshot_as_png_large_plot(webdriver): layout = Plot(x_range=Range1d(), y_range=Range1d(), plot_height=800, plot_width=800, toolbar_location=None, outline_line_color=None, background_fill_color=None, border_fill_color=None) bie.get_screenshot_as_png(layout, driver=webdriver) # LC: Although the window size doesn't match the plot dimensions (unclear # why), the window resize allows for the whole plot to be captured assert webdriver.get_window_size() == {'width': 1366, 'height': 768}
def set_data(umsatz=3000, anteil_hausmarke=66): # method for setting data based on some value bonus = 0.00 if umsatz >= 1750: bonus = 0.03 provision_andere = umsatz*(0.2+bonus) provision_eigenmarke = umsatz*(0.23+bonus) provision_kombiniert = (anteil_hausmarke/100) * provision_eigenmarke + (100 - anteil_hausmarke)/100 * provision_andere provision_neu_28 = (umsatz / 1.19) * 0.28 provision_neu_30 = (umsatz / 1.19) * 0.30 provision_neu_32 = (umsatz / 1.19) * 0.32 quellen = [provisionsquellen[0].format(int(100*(0.2+bonus))), provisionsquellen[1].format(int(100*(0.23+bonus))), provisionsquellen[2].format(anteil_hausmarke, 100-anteil_hausmarke), provisionsquellen[3], provisionsquellen[4], provisionsquellen[5]] provision = [provision_andere, provision_eigenmarke, provision_kombiniert, provision_neu_28, provision_neu_30, provision_neu_32] data_source.data = dict(provision=provision, line_limits=[0] + [len(provision)+1]*5, provision_neu_28=[provision_neu_28]*6, provision_neu_30=[provision_neu_30]*6, provision_neu_32=[provision_neu_32]*6, quellen=quellen, text=['{} €'.format(int(p)) for p in provision], color=COLORMAP) plot.x_range.factors = quellen plot.y_range = Range1d(0, 1.4*max(provision))
def update_figure_properties(self, plane: Plane, image: np.ndarray): """ Updates the figure's properties according to the properties of the image. Parameters ---------- plane : Plane One of the three planes of the 3D data. """ width, height = image.shape[1], image.shape[0] figure = self.get_figure_model(plane) figure.plot_width = min(int(width * 1.8), 405) figure.plot_height = int(height * 1.8) figure.x_range = Range1d(0, width) figure.y_range = Range1d(0, height)
def get_chi_plot(job): """Render the chi vs #state plot using Bokeh""" source = get_chi_plot_source(job) # If the error bars are huge, truncate them so we can see the best chi # in the default view ymax = min(max(source.data['val']) * 2., max(source.data['valerr']) + 0.01) p = bokeh.plotting.figure(x_axis_label='# of states', y_axis_label='χ²', plot_width=300, plot_height=250, y_range=Range1d(0, ymax, bounds=(0, None))) p.xaxis.ticker = source.data['nstate'] p.yaxis.axis_label_text_font_style = 'normal' p.yaxis.axis_label_text_font_size = '1.2em' p.xaxis.axis_label_text_font_style = 'normal' p.xaxis.axis_label_text_font_size = '1.2em' p.xgrid.visible = p.ygrid.visible = False p.toolbar.autohide = True p.outline_line_color = None p.add_tools(HoverTool(tooltips="@desc")) p.segment(x0='nstate', x1='nstate', y0='val', y1='valerr', source=source) p.rect('nstate', 'valerr', 0.1, 0.01, source=source) p.vbar(x='nstate', top='val', width=0.2, source=source, hover_line_color='black', line_color=None) script, div = bokeh.embed.components(p) return {'js': script, 'div': div}
def test_get_screenshot_as_png_with_driver(): layout = Plot(x_range=Range1d(), y_range=Range1d(), plot_height=20, plot_width=20, toolbar_location=None, outline_line_color=None, background_fill_color=None, border_fill_color=None) driver = webdriver.PhantomJS(service_log_path=os.path.devnull) png = bie.get_screenshot_as_png(layout, driver=driver) # Have to manually clean up the driver session driver.quit() assert png.size == (20, 20) # a 20x20px image of transparent pixels assert png.tobytes() == ("\x00"*1600).encode()
def newPlot(self): #Constants xr = Range1d(start=int(max(self.ppmScale) + 1), end=int(min(self.ppmScale) - 1)) self.plot = figure(x_axis_label='ppm', x_range=xr, toolbar=CustomToolbar(), tools="pan,save,reset", plot_width=self.WIDTH, plot_height=self.HEIGHT) # Remove grid from plot self.plot.xgrid.grid_line_color = None self.plot.ygrid.grid_line_color = None horizontalBoxZoomTool = HorizontalBoxZoomTool() self.plot.add_tools(horizontalBoxZoomTool) self.plot.toolbar.active_drag = horizontalBoxZoomTool fixedWheelZoomTool = FixedWheelZoomTool(dimensions="height") self.plot.add_tools(fixedWheelZoomTool) self.plot.toolbar.active_scroll = fixedWheelZoomTool fixedZoomOutTool = FixedZoomOutTool(factor=0.4) self.plot.add_tools(fixedZoomOutTool) hoverTool = HoverTool(tooltips="($x, $y)") self.plot.add_tools(hoverTool)
def test_get_svgs_with_svg_present(): def fix_ids(svg): svg = re.sub(r'id="\w{12}"', 'id="X"', svg) svg = re.sub(r'url\(#\w{12}\)', 'url(#X)', svg) return svg layout = Plot(x_range=Range1d(), y_range=Range1d(), plot_height=20, plot_width=20, toolbar_location=None, outline_line_color=None, border_fill_color=None, background_fill_color="red", output_backend="svg") svg0 = fix_ids(bie.get_svgs(layout)[0]) driver = create_webdriver() try: svg1 = fix_ids(bie.get_svgs(layout)[0]) finally: terminate_webdriver( driver) # Have to manually clean up the driver session svg2 = ( '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ' 'width="20" height="20" style="width: 20px; height: 20px;">' '<defs>' '<clipPath id="X"><path fill="none" stroke="none" d=" M 5 5 L 15 5 L 15 15 L 5 15 L 5 5 Z"/></clipPath>' '<clipPath id="X"><path fill="none" stroke="none" d=" M 5 5 L 15 5 L 15 15 L 5 15 L 5 5 Z"/></clipPath>' '</defs>' '<g>' '<g transform="scale(1,1) translate(0.5,0.5)">' '<rect fill="#FFFFFF" stroke="none" x="0" y="0" width="20" height="20"/>' '<rect fill="red" stroke="none" x="5" y="5" width="10" height="10"/>' '<g/>' '<g clip-path="url(#X)"><g/></g>' '<g clip-path="url(#X)"><g/></g>' '<g/>' '</g>' '</g>' '</svg>') assert svg0 == svg2 assert svg1 == svg2
def test_get_screenshot_as_png_large_plot(): layout = Plot(x_range=Range1d(), y_range=Range1d(), plot_height=800, plot_width=800, toolbar_location=None, outline_line_color=None, background_fill_color=None, border_fill_color=None) driver = webdriver.PhantomJS(service_log_path=os.path.devnull) assert driver.get_window_size() == {'width': 400, 'height': 300} bie.get_screenshot_as_png(layout, driver=driver) # LC: Although the window size doesn't match the plot dimensions (unclear # why), the window resize allows for the whole plot to be captured assert driver.get_window_size() == {'width': 1366, 'height': 768} # Have to manually clean up the driver session driver.quit()
def _get_figure_instance(self, xlabel="x label name", ylabel="y label name", xlim=None, ylim=None, width=None, height=None, **kwargs): """return a figure instance Args: kwargs: parameters for creating a figure in bokeh xlabel: (Default value = "x label name") ylabel: (Default value = "y label name") xlim: (Default value = None) ylim: (Default value = None) width: (Default value = None) height: (Default value = None) **kwargs: Returns: a bokeh plot figure obj """ f = figure(plot_width=self.w, plot_height=self.h, output_backend='webgl', toolbar_location='above', active_scroll='wheel_zoom', tools=self.default_tools, **kwargs) f.xaxis.axis_label = xlabel f.yaxis.axis_label = ylabel if xlim is not None and len(xlim) == 2: f.x_range = Range1d(xlim[0], xlim[1]) if ylim is not None and len(ylim) == 2: f.y_range = Range1d(ylim[0], ylim[1]) if width is not None: f.plot_width = width if height is not None: f.plot_height = height return f
def test__check_compatible_scale_and_ranges_compat_numeric(): plot = Plot(x_scale=LinearScale(), x_range=Range1d()) check = plot._check_compatible_scale_and_ranges() assert check == [] plot = Plot(y_scale=LogScale(), y_range=DataRange1d()) check = plot._check_compatible_scale_and_ranges() assert check == []
def test_ImageRGB(self): source = _SourceShim(ar_downsample.InterpolateColor) result = ar_downsample.mapping(source) expected = { 'x_range': Range1d(start=0, end=0), 'y_range': Range1d(start=0, end=0) } self.assertEquals(len(expected), len(result)) self.assertEquals(sorted(expected.keys()), sorted(result.keys())) source = _SourceShim(ar_downsample.InterpolateColor, "A", "B", "C") result = ar_downsample.mapping(source) expected['A'] = source.defVal expected['B'] = source.defVal expected['C'] = source.defVal self.assertEquals(sorted(expected.keys()), sorted(result.keys()))
def update_parameters(self, attrname, old, new): # Get the current slider values self.pendulum_length = self.pendulum_length_slider.value self.target_cart_position = self.target_cart_position_slider.value self.gravity = self.gravity_slider.value theta0 = self.pendulum_angle_slider.value pendulum_mass = self.pendulum_mass_slider.value cart_mass = self.cart_mass_slider.value x0 = self.start_cart_position_slider.value x = self.target_cart_position cart_rub = 0.1 pendulum_inertia = (self.pendulum_length**2) * pendulum_mass theta = 0 # simulator = FullSimulator.FullSimulator(0.5, 0.1, 0.2, 0.6, 0.006, 0, 0.314, 0, 0, 9.81, tk=50, tp=0.01) self.simulator = RealTimeSimulator.RealTimeSimulator( cart_mass, cart_rub, pendulum_mass, self.pendulum_length, pendulum_inertia, x0, theta0, x, theta, self.gravity) print(cart_mass, cart_rub, pendulum_mass, self.pendulum_length, pendulum_inertia, x0, theta0, x, theta, self.gravity) # (0.5, 0.1, 0.2, 0.6, 0.006, 0, 0, 2, 0, 9.81) self.simulator.start() self.time_results, self.position_results, self.angle_results = self.simulator.get_result( ) self.time_results = [self.time_results] self.position_results = [self.position_results] self.angle_results = [self.angle_results] self.ip_temp_dict['ball_size'] = [pendulum_mass * 10] self.frame = 0 self.set_target_position(0, 0, 0) # drawing zaleznosci czasowe (graph_under) -> # update xyranges # time_min = min(self.time_results) # time_max = max(self.time_results) # pos_min = min(self.position_results) # pos_max = max(self.position_results) self.plot_position.y_range = Range1d(-6, 6) self.plot_theta.y_range = Range1d(-np.pi / 3 * 2, np.pi / 3 * 2) # self.animation.x_range = Range1d(pos_min-10, pos_max+10) # fix it maybe # update CDS self.draw_next_frame()
def test_span(self): self.assertEquals(0, ar_downsample._span(Range1d(start=0, end=0))) self.assertEquals(2, ar_downsample._span(Range1d(start=0, end=2))) self.assertEquals(2, ar_downsample._span(Range1d(start=-2, end=0))) self.assertEquals(4, ar_downsample._span(Range1d(start=-2, end=2))) self.assertEquals(4, ar_downsample._span(Range1d(start=2, end=-2))) self.assertEquals(3, ar_downsample._span(Range1d(start=None, end=3))) self.assertEquals(3, ar_downsample._span(Range1d(start=3, end=None))) self.assertEquals(0, ar_downsample._span(Range1d(start=None, end=None)))