def test_reset_triggers_factorrange_callback(output_file_url, selenium): x_range = FactorRange(factors=["a", "b", "c"]) x_range.callback = CustomJS(code='alert("plot reset")') y_range = Range1d() # Make plot and add a range callback that generates an alert plot = make_plot(x_range, y_range, tools='reset') # Save the plot and start the test save(plot) selenium.get(output_file_url) assert has_no_console_errors(selenium) # Tap the plot and test for alert reset_button = selenium.find_element_by_class_name('bk-tool-icon-reset') click_element_at_position(selenium, reset_button, 10, 10) alert = selenium.switch_to_alert() assert alert.text == 'plot reset'
def test__check_compatible_scale_and_ranges_incompat_numeric_scale_and_factor_range( ) -> None: plot = Plot(x_scale=LinearScale(), x_range=FactorRange()) check = plot._check_compatible_scale_and_ranges() assert check != []
def get_range_instance(): return FactorRange('foo', 'bar')
def plot_dual_axis_bar_line(df: pd.DataFrame, title: str, groups_name: str, bar_target_name_variable0: str, bar_target_name_variable1: str, bar_variables: list, line_target_name: str, left_axis_y_label: str, right_axis_y_label: str, bar_colours: list = ["#8c9eff", "#536dfe"], plot_height=300, plot_width=700): """ :param df: wide dataframe with data for each bar, the categorical valriables, the grouping and line :param title: title of plot :param groups_name: name for the column where the groups are :param bar_target_name_variable0: name for the bar chart of the first variable :param bar_target_name_variable1: name for the bar chart of the second variable :param bar_variables: names of the variables used as a list :param line_target_name: name of the column for the line chart :param left_axis_y_label: label name for the left axis (related to the bar chart) :param right_axis_y_label: label name for the right axis (related to the line chart) :param bar_colours: colours used for each variable :param plot_height: height of the plot :param plot_width: width of the plot :return: figure with bar chart in left axis and line chart in right axis """ df = df.copy() groups = df[groups_name].unique() tp_rates = [[ df.loc[index, bar_target_name_variable0], df.loc[index, bar_target_name_variable1] ] for index, row in df.iterrows()] tp_rates = [item for sublist in tp_rates for item in sublist] index_tuple = [(group_, bar_variable) for group_ in groups for bar_variable in bar_variables] colours = bar_colours * len(groups) p = figure(x_range=FactorRange(*index_tuple), plot_height=plot_height, plot_width=plot_width, title=title, tools="save") """ Bar chart specific """ source = ColumnDataSource(data=dict(x=index_tuple, counts=tp_rates, profits=list(df[line_target_name]), colours=colours)) p.vbar(x='x', top='counts', width=0.9, source=source, color='colours') """ Line chart specific """ p.line(x=list(groups), y=list(df[line_target_name]), y_range_name=right_axis_y_label, line_color="#ffca28", line_width=2) p.circle(x=list(groups), y=list(df[line_target_name]), y_range_name=right_axis_y_label, color="#ffca28", size=7) """ Axis specific """ p.y_range = Range1d(0, 1) p.yaxis.axis_label = left_axis_y_label p.extra_y_ranges = { right_axis_y_label: Range1d(start=0, end=max(df[line_target_name]) * 1.2) } p.add_layout( LinearAxis(y_range_name=right_axis_y_label, axis_label=right_axis_y_label), 'right') p.yaxis[0].formatter = NumeralTickFormatter(format='0 %') p.x_range.range_padding = 0.1 p.xaxis.major_label_orientation = 1 p.xgrid.grid_line_color = None return p
def bokeh_scatter(data, fig_dir, factor_name, threshold=0.05): plot_data = dict( x=data.index.tolist(), pval_adj=data['p.adjusted'].tolist(), neg_log10_pval_adj=data['neg_log_padj'].tolist(), R2=data['R2'].tolist(), upper=[data['neg_log_padj'].max() * 1.2] * len(data), lower=[-np.log10(threshold)] * len(data), n1=data['n1'].tolist(), n2=data['n2'].tolist(), ) plots = [] factors = pd.MultiIndex.get_level_values(data.index, 1).unique() palette = Category10[10] + Dark2[8] + Accent[8] index_cmap = factor_cmap('x', palette=palette, factors=sorted(factors), start=1, end=2) tooltips = [('R2', '@R2'), ('adjusted p-value', '@pval_adj'), ('#samples in {} 1'.format(factor_name), '@n1'), ('#samples in {} 2'.format(factor_name), '@n2')] titles = { 'neg_log10_pval_adj': 'Permanova test: -log10[adjusted p-value]', 'R2': 'Permanova test: R2 score' } for metric, title in titles.items(): p = figure(title=title, x_range=FactorRange(*plot_data['x']), tooltips=tooltips) p.vbar(x='x', top=metric, width=0.9, source=plot_data, line_color="white", fill_color=index_cmap) if metric == 'neg_log10_pval_adj': p.line( list(range(len(data) + len(factors))), [-np.log10(threshold)] * (len(data) + len(factors)), line_color='grey', line_dash='dashed', line_width=1, line_alpha=0.5, legend_label="{:.0%} significance threshold".format(threshold)) band = Band(base='x', lower='lower', upper='upper', level='underlay', source=ColumnDataSource(plot_data), line_dash='dashed', fill_alpha=0.5, line_width=1, line_color='black') p.add_layout(band) p.legend.background_fill_alpha = 0.0 p.xaxis.major_label_orientation = "vertical" p.xaxis.axis_label_text_font_size = "10pt" plots.append(p) grid = gridplot(plots, ncols=1, plot_width=1500, plot_height=500) output_file(f"{fig_dir}/permanova_results_{factor_name}.html") save(grid)
def make_axis(axis, size, factors, dim, flip=False, rotation=0, label_size=None, tick_size=None, axis_height=35): factors = list(map(dim.pprint_value, factors)) nchars = np.max([len(f) for f in factors]) ranges = FactorRange(factors=factors) ranges2 = Range1d(start=0, end=1) axis_label = dim_axis_label(dim) reset = "range.setv({start: 0, end: range.factors.length})" ranges.callback = CustomJS(args=dict(range=ranges), code=reset) axis_props = {} if label_size: axis_props['axis_label_text_font_size'] = value(label_size) if tick_size: axis_props['major_label_text_font_size'] = value(tick_size) tick_px = font_size_to_pixels(tick_size) if tick_px is None: tick_px = 8 label_px = font_size_to_pixels(label_size) if label_px is None: label_px = 10 rotation = np.radians(rotation) if axis == 'x': align = 'center' # Adjust height to compensate for label rotation height = int(axis_height + np.abs(np.sin(rotation)) * ((nchars * tick_px) * 0.82)) + tick_px + label_px opts = dict(x_axis_type='auto', x_axis_label=axis_label, x_range=ranges, y_range=ranges2, plot_height=height, plot_width=size) else: # Adjust width to compensate for label rotation align = 'left' if flip else 'right' width = int(axis_height + np.abs(np.cos(rotation)) * ((nchars * tick_px) * 0.82)) + tick_px + label_px opts = dict(y_axis_label=axis_label, x_range=ranges2, y_range=ranges, plot_width=width, plot_height=size) p = Figure(toolbar_location=None, tools=[], **opts) p.outline_line_alpha = 0 p.grid.grid_line_alpha = 0 if axis == 'x': p.yaxis.visible = False axis = p.xaxis[0] if flip: p.above = p.below p.below = [] p.xaxis[:] = p.above else: p.xaxis.visible = False axis = p.yaxis[0] if flip: p.right = p.left p.left = [] p.yaxis[:] = p.right axis.major_label_orientation = rotation axis.major_label_text_align = align axis.major_label_text_baseline = 'middle' axis.update(**axis_props) return p
r = kw['edge_renderer'] assert r.glyph.line_color == "purple" assert r.selection_glyph.line_color == "blue" assert r.nonselection_glyph.line_color == "yellow" assert r.hover_glyph.line_color == "red" assert r.muted_glyph.line_color == "orange" assert r.glyph.line_width == 23 assert r.selection_glyph.line_width == 23 assert r.nonselection_glyph.line_width == 23 assert r.hover_glyph.line_width == 23 assert r.muted_glyph.line_width == 23 _RANGES = [Range1d(), DataRange1d(), FactorRange()] class Test__get_axis_class(object): @pytest.mark.parametrize('range', _RANGES) @pytest.mark.unit def test_axis_type_None(self, range): assert (bph._get_axis_class(None, range, 0)) == (None, {}) assert (bph._get_axis_class(None, range, 1)) == (None, {}) @pytest.mark.parametrize('range', _RANGES) @pytest.mark.unit def test_axis_type_linear(self, range): assert (bph._get_axis_class("linear", range, 0)) == (LinearAxis, {}) assert (bph._get_axis_class("linear", range, 1)) == (LinearAxis, {})
df.set_index('city', inplace=True) ######################### checkbox_determinants_labels = list(cols) determinants_selection = CheckboxGroup(labels=list( np.sort(checkbox_determinants_labels)), active=[10, 11]) ######################### x, counts = create_x_and_counts(df=df, cities=cities) source = ColumnDataSource( data=dict(x=x, counts=counts, colors=())) # ,colors=(sum(zip(Spectral6, Spectral6), ()) p = figure(x_range=FactorRange(*source.data['x']), plot_width=1400, plot_height=850, title="Determinants Comparison", toolbar_location=None, tools="") p.xaxis.major_label_orientation = "vertical" city_selection.on_change('active', update_plot) determinants_selection.on_change('active', update_plot) checkbox_cities_column = column(city_selection) checkbox_determinants_column = column(determinants_selection) bokeh_doc = curdoc()
def on_session_created(session_context): ''' If present, this function is called when a session is created. ''' import_data.retrieve_data() rigs_list = [] rigs_list = [str(item) for item in uHelper.rigs_list] default_rig_number = '' if 1 <= len(rigs_list): default_rig_number = rigs_list[0] uHelper.rigs_combx = Select(title='Rigs:', value=default_rig_number, width=120, sizing_mode=uHelper.sizing_mode, options=uHelper.update_combBx_values( '', rigs_list)) jobs_list = [] jobs_list = [str(item) for item in uHelper.jobs_list] default_job_number = '' if 1 <= len(jobs_list): default_job_number = jobs_list[0] uHelper.default_job_number = default_job_number uHelper.jobs_list = jobs_list uHelper.jobs_combx = Select(title='Jobs:', value=default_job_number, width=120, sizing_mode=uHelper.sizing_mode, options=uHelper.update_combBx_values( '', jobs_list)) # 2. checkbox group uHelper.checkbox_group_1 = CheckboxGroup(labels=["Build", "Lateral", "Vertical"], \ active=[], \ name = 'wellSelection') uHelper.checkbox_group_2 = CheckboxGroup(labels=["Driller", "Novos", "Hybrid"], \ active=[], \ name = 'connectionType') uHelper.checkbox_group_3 = CheckboxGroup(labels=["B2S", "S2S", "S2B", "Survey", "BackReam", "Friction Test"], \ active=[], \ name = 'connectionPhase') rig, job = uHelper.rigs_combx.value, uHelper.jobs_combx.value # 1st chart uHelper.update_drillingconn_wellsect_queue = queue.Queue() uHelper.update_drillingconn_wellsect_event = threading.Event() update_drillingconn_wellsect_thread = Thread(name = 'update_drillingconn_wellsect_thread', \ target = lambda q, arg1, arg2, arg3, arg4: \ q.put(drillingconn_wellsect_plot.update_well_selection_data(arg1, arg2, arg3, arg4)), \ args = (uHelper.update_drillingconn_wellsect_queue, \ uHelper.update_drillingconn_wellsect_event, \ uHelper.all_connection_dict, rig, job)) update_drillingconn_wellsect_thread.start() uHelper.update_drillingconn_wellsect_event.wait() well_connection_colors, x, well_connnection_counts, well_connnection_data = uHelper.update_drillingconn_wellsect_queue.get( ) uHelper.well_connnection_source = ColumnDataSource(data = dict(colors = well_connection_colors, \ x = x, \ counts = well_connnection_counts)) well_connection_chart = figure(x_range = FactorRange(*x), \ plot_width = uHelper.plot_width, \ plot_height = 430, \ sizing_mode = uHelper.sizing_mode, \ title = "Drilling Connection Breakdown By Well Section") well_connection_chart.vbar(x = 'x', \ width = 0.2, \ bottom = 0, \ top = 'counts', \ color = 'colors', \ source = uHelper.well_connnection_source) total_connections = sum(well_connnection_counts) uHelper.well_connection_textbox_source = ColumnDataSource(data = dict(x = [600,], \ y = [250,], \ txt = ['Total Connections: %d' % (total_connections),])) well_connection_chart_textbox = LabelSet(x = 'x', \ y = 'y', \ x_units = 'screen', \ y_units = 'screen', \ text = 'txt', \ source = uHelper.well_connection_textbox_source,\ text_font_size = "12pt", border_line_color='black', \ border_line_width = 1,\ text_font_style = 'bold') well_connection_chart.add_layout(well_connection_chart_textbox) well_connection_chart.title.align = 'center' well_connection_chart.title.text_font_size = '15pt' well_connection_chart.toolbar.active_drag = None well_connection_chart.toolbar.logo = None well_connection_chart.toolbar_location = None well_connection_chart.y_range.start = 0 well_connection_chart.x_range.range_padding = 0.1 well_connection_chart.xaxis.major_label_orientation = 1 well_connection_chart.xgrid.grid_line_color = None for well_item in well_connnection_data['well_selection']: for sub_item in well_connnection_data['Driller']: well_connection_chart.add_tools( HoverTool(tooltips=[(str(well_item), "@counts")])) ### 2nd chart(b2s s2b) uHelper.update_b2s_s2b_queue = queue.Queue() uHelper.update_b2s_s2b_event = threading.Event() update_b2s_s2b_thread = threading.Thread(name = 'update_b2s_s2b_thread', \ target = lambda q, arg1, arg2, arg3, arg4: \ q.put(b2s_s2b_plot.update_b2s_s2b_data(arg1, arg2, arg3, arg4)), \ args = (uHelper.update_b2s_s2b_queue, \ uHelper.update_b2s_s2b_event, \ uHelper.novos_connection_table, \ rig, \ job)) update_b2s_s2b_thread.start() uHelper.update_b2s_s2b_event.wait() b2s_canceled_list, b2s_completed_list, \ b2s_exception_list,b2s_failed_list, \ s2b_canceled_list, s2b_completed_list, \ s2b_exception_list, s2b_failed_list = uHelper.update_b2s_s2b_queue.get() uHelper.b2s_s2b_status = ["Canceled", "Completed", "Exception", "Failed"] uHelper.b2s_s2b_colors = ["#F2C80F", "#00ff0d", "#F2C80F", "#ff4600"] b2s_figure = figure(x_range = uHelper.b2s_connection_phase, \ plot_width = 600, \ plot_height = 430, \ sizing_mode = uHelper.sizing_mode, \ title = "Bottom to Slip") uHelper.b2s_datasource = ColumnDataSource(data = dict(b2s_connection_phase = uHelper.b2s_connection_phase, \ Canceled = b2s_canceled_list, \ Completed = b2s_completed_list, \ Exception = b2s_exception_list, \ Failed = b2s_failed_list)) b2s_figure.vbar_stack(uHelper.b2s_s2b_status, \ x='b2s_connection_phase', \ width = 0.2, \ color = uHelper.b2s_s2b_colors, \ source = uHelper.b2s_datasource) b2s_figure.title.align = 'center' b2s_figure.toolbar.active_drag = None b2s_figure.toolbar.logo = None b2s_figure.toolbar_location = None b2s_figure.y_range.start = 0 b2s_figure.x_range.range_padding = 0.1 b2s_figure.xaxis.major_label_orientation = 1 b2s_figure.xgrid.grid_line_color = None b2s_figure.ygrid.grid_line_color = None s2b_figure = figure(x_range = uHelper.s2b_connection_phase, \ plot_width = 670, \ plot_height = 430, \ sizing_mode = uHelper.sizing_mode, \ title = "Slip to Bottom") uHelper.s2b_datasource = ColumnDataSource(data = dict(s2b_connection_phase = uHelper.s2b_connection_phase, \ Canceled = s2b_canceled_list, \ Completed = s2b_completed_list, \ Exception = s2b_exception_list, \ Failed = s2b_failed_list)) s2b_figure.vbar_stack(uHelper.b2s_s2b_status, \ x = 's2b_connection_phase', \ width = 0.2, \ color = uHelper.b2s_s2b_colors, \ source = uHelper.s2b_datasource, \ legend= [value(x) for x in uHelper.b2s_s2b_status]) s2b_figure.title.align = 'center' s2b_figure.toolbar.active_drag = None s2b_figure.toolbar.logo = None s2b_figure.toolbar_location = None s2b_figure.y_range.start = 0 s2b_figure.x_range.range_padding = 0.1 s2b_figure.xaxis.major_label_orientation = 1 s2b_figure.xgrid.grid_line_color = None s2b_figure.ygrid.grid_line_color = None s2b_figure.legend.location = "top_right" s2b_figure.legend.orientation = "vertical" new_legend = s2b_figure.legend[0] s2b_figure.legend[0].plot = None s2b_figure.add_layout(new_legend, 'right') line_figure = figure(x_range=(0, 100), \ y_range=(0, 300), \ plot_width = 120, \ plot_height = 430) line_figure.line(x=[50, 50], \ y= [0, 300], \ line_width = 3, \ line_color='black') line_figure.xaxis.visible = None line_figure.yaxis.visible = None line_figure.toolbar.logo = None line_figure.toolbar_location = None line_figure.toolbar.active_drag = None line_figure.min_border_left = 10 line_figure.min_border_right = 10 line_figure.min_border_top = 0 line_figure.min_border_bottom = 0 mTicker = uHelper.customize_ticker() uHelper.novos_counts = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] uHelper.novos_config_source = ColumnDataSource(data = dict(x = uHelper.novos_config_variables, \ hBarColors = uHelper.hBar_color_list, \ counts = uHelper.novos_counts, \ nclegends = uHelper.novos_config_legends)) uHelper.novos_config_plot = figure(y_range = FactorRange(*uHelper.novos_config_variables), \ plot_width = 800, \ plot_height = 250, \ title="NOVOS Config Details", \ toolbar_location = None, \ tools = "", \ y_axis_location = 'right', \ sizing_mode = uHelper.sizing_mode, \ id = "novos_config_plot_id") uHelper.novos_config_plot.hbar(y = 'x', \ right = 0, \ left = 'counts', \ height = 0.5, \ color = 'hBarColors', \ source = uHelper.novos_config_source, \ legend = 'nclegends') max_counts = max(uHelper.novos_counts) max_counts = int(max_counts) if max_counts <= 5: uHelper.novos_config_plot.x_range.start = 5 else: uHelper.novos_config_plot.x_range.start = max_counts uHelper.novos_config_plot.x_range.end = 0 uHelper.novos_config_plot.ygrid.grid_line_color = None uHelper.novos_config_plot.title.align = 'center' uHelper.novos_config_plot.title.text_font_size = '15pt' uHelper.novos_config_plot.legend.location = "top_left" uHelper.novos_config_plot.legend.orientation = "horizontal" uHelper.novos_config_plot.legend.border_line_width = 0 uHelper.novos_config_plot.legend.border_line_color = "white" uHelper.novos_config_plot.legend.border_line_alpha = 0 new_legend = uHelper.novos_config_plot.legend[0] uHelper.novos_config_plot.legend[0].plot = None uHelper.novos_config_plot.add_layout(new_legend, 'above') novos_config_columns = [ TableColumn(field="variable", title="variables"), TableColumn(field="hole_depth_ft", title="hole depth"), TableColumn(field="value", title="value"), TableColumn(field="unit", title="unit") ] uHelper.novos_config_value_and_units_source = ColumnDataSource(data = dict(variable = uHelper.novos_config_variables, \ hole_depth_ft = uHelper.novos_config_hole_depth_ft_list, \ value = uHelper.novos_value_list, \ unit = uHelper.novos_unit_list)) novos_config_data_table = DataTable(source = uHelper.novos_config_value_and_units_source, \ columns = novos_config_columns, \ width = 500, \ height = 250, sizing_mode = uHelper.sizing_mode) novos_config_table_plot = widgetbox(novos_config_data_table) novos_config.update_novos_config_counts(uHelper.novos_config_source, \ uHelper.novos_config_table, \ uHelper.novos_config_variables, \ job) novos_config.update_novos_config_value_and_units(uHelper.novos_config_table, \ rig, \ job) uHelper.main_plot = figure(x_range = FactorRange(), \ y_range = (0, 50), \ plot_width = uHelper.plot_width - uHelper.conn_type_comp_txtbx_offset, \ plot_height = 400, \ tools = "tap, hover, pan, box_zoom, reset", \ sizing_mode = uHelper.sizing_mode, \ title="Overall Connection Times", \ tooltips = [('Duration', '@Periods'),]) uHelper.main_plot.xaxis.ticker = mTicker uHelper.main_plot.title.align = 'center' uHelper.main_plot.legend.click_policy = "hide" uHelper.main_plot.title.text_font_size = '15pt' uHelper.main_plot.xaxis.major_label_orientation = 1 uHelper.main_plot.x_range.factors = [] uHelper.main_plot.toolbar.logo = None uHelper.main_plot.toolbar_location = "above" uHelper.main_plot.css_classes = ["mainplot"] uHelper.mainplot_source = ColumnDataSource(data = dict(HoleDepthRef = [], \ HoleDepth = [], \ VBarTop = [], \ VBarBottom = [], \ VBarColors = [], \ VBarType = [], \ Periods = [])) main_plot_vbars = uHelper.main_plot.vbar(x = 'HoleDepth', \ width = 0.1, \ bottom = 'VBarBottom', \ top = 'VBarTop', \ color = 'VBarColors', \ source = uHelper.mainplot_source, \ legend = 'VBarType') uHelper.main_plot.legend.location = "top_left" uHelper.main_plot.legend.orientation = "horizontal" uHelper.main_plot.legend.border_line_width = 0 uHelper.main_plot.legend.border_line_color = "white" uHelper.main_plot.legend.border_line_alpha = 0 new_legend = uHelper.main_plot.legend[0] uHelper.main_plot.legend[0].plot = None uHelper.main_plot.add_layout(new_legend, 'above') main_textbox_plot = figure( plot_width = uHelper.conn_type_comp_txtbx_offset, \ x_range =(0, 200), \ y_range = (0, 250), \ plot_height = 400, \ sizing_mode = uHelper.sizing_mode, \ id = "main_textbox_plot_id") main_textbox_plot.xaxis.visible = None main_textbox_plot.yaxis.visible = None main_textbox_plot.toolbar.logo = None main_textbox_plot.toolbar_location = None main_textbox_plot.toolbar.active_drag = None main_textbox_plot.xgrid.grid_line_color = None main_textbox_plot.ygrid.grid_line_color = None main_textbox_plot.x_range.start = 0 main_textbox_plot.y_range.start = 0 main_textbox_plot.min_border_left = 0 main_textbox_plot.min_border_right = 10 main_textbox_plot.min_border_top = 0 main_textbox_plot.min_border_bottom = 0 main_textbox_plot.rect(x = 80, \ y = 130, \ width = 140, \ height = 140, \ line_color = '#666666', \ line_width = 2, \ color = "white") uHelper.main_plot_ckbx_txtbx_source = ColumnDataSource(data = dict(x = [30, 30], \ y = [230, 210], \ txt = uHelper.plot_ckbx_textbox_text)) main_plot_ckbx_textbox = LabelSet(x = 'x', \ y = 'y', \ text = 'txt', \ source = uHelper.main_plot_ckbx_txtbx_source,\ text_font_size = "10pt", \ text_font_style = 'bold') main_textbox_plot.add_layout(main_plot_ckbx_textbox) uHelper.main_plot_textbox_source = ColumnDataSource(data = dict(x = [30, 30, 30, 30, 30, 30, 30, 30], \ y = [180, 165, 145, 130, 110, 95, 75, 60], \ txt = uHelper.plot_textbox_text)) uHelper.main_textbox = LabelSet(x = 'x', \ y = 'y', \ text = 'txt', \ source = uHelper.main_plot_textbox_source,\ text_font_size = "10pt", \ text_font_style = 'bold') main_textbox_plot.add_layout(uHelper.main_textbox) vs_plot_textbox = figure(x_range = (0, 200), \ y_range = (0, 800), \ plot_width = uHelper.conn_type_comp_txtbx_offset, \ plot_height = 800, \ sizing_mode = uHelper.sizing_mode) vs_plot_textbox.xaxis.visible = None vs_plot_textbox.yaxis.visible = None vs_plot_textbox.toolbar.logo = None vs_plot_textbox.toolbar_location = None vs_plot_textbox.toolbar.active_drag = None vs_plot_textbox.xgrid.grid_line_color = None vs_plot_textbox.ygrid.grid_line_color = None vs_plot_textbox.x_range.start = 0 vs_plot_textbox.y_range.start = 0 vs_plot_textbox.min_border_left = 0 vs_plot_textbox.min_border_right = 10 vs_plot_textbox.min_border_top = 0 vs_plot_textbox.min_border_bottom = 0 uHelper.vs_ckbx_textbox_source = ColumnDataSource(data = dict(x = [30, 30], \ y = [775, 750], \ txt = uHelper.plot_ckbx_textbox_text)) vs_ckbx_text = LabelSet(x = 'x', \ y = 'y', \ text = 'txt', \ source = uHelper.vs_ckbx_textbox_source,\ text_font_size = "10pt", \ text_font_style = 'bold') vs_plot_textbox.add_layout(vs_ckbx_text) uHelper.driller_vs_textbox_source = ColumnDataSource(data = dict(x = [35, 35, 35, 35, 35, 35, 35, 35], \ y = [708, 690, 665, 645, 620, 605, 580, 560], \ txt = uHelper.plot_textbox_text)) driller_vs_text = LabelSet(x = 'x', \ y = 'y', \ text = 'txt', \ source = uHelper.driller_vs_textbox_source,\ text_font_size = "10pt", \ text_font_style = 'bold') vs_plot_textbox.add_layout(driller_vs_text) uHelper.hybrid_vs_textbox_source = ColumnDataSource(data = dict(x = [35, 35, 35, 35, 35, 35, 35, 35], \ y = [468, 450, 425, 405, 380, 350, 335, 315], \ txt = uHelper.plot_textbox_text)) hybrid_vs_text = LabelSet(x = 'x', \ y = 'y', \ text = 'txt', \ source = uHelper.hybrid_vs_textbox_source,\ text_font_size = "10pt", \ text_font_style = 'bold') vs_plot_textbox.add_layout(hybrid_vs_text) uHelper.novos_vs_textbox_source = ColumnDataSource(data = dict(x = [35, 35, 35, 35, 35, 35, 35, 35], \ y = [218, 200, 175, 155, 130, 110, 85, 65], \ txt = uHelper.plot_textbox_text)) novos_vs_text = LabelSet(x = 'x', \ y = 'y', \ text = 'txt', \ source = uHelper.novos_vs_textbox_source,\ text_font_size = "10pt", \ text_font_style = 'bold') vs_plot_textbox.add_layout(novos_vs_text) vs_plot_textbox.rect(x = 100, \ y = 640, \ width = 150, \ height = 170, \ line_color = '#666666', \ line_width = 2, \ color = "white") vs_plot_textbox.rect(x = 100, \ y = 400, \ width = 150, \ height = 170, \ line_color = '#666666', \ line_width = 2, \ color = "white") vs_plot_textbox.rect(x = 100, \ y = 150, \ width = 150, \ height = 170, \ line_color = '#666666', \ line_width = 2, \ color = "white") uHelper.all_novosconfig_circle_source = uHelper.create_novosconfig_all_circle_source( uHelper.novos_config_variables) uHelper.create_novosconfig_circles(uHelper.main_plot, uHelper.all_novosconfig_circle_source) # layout uHelper.m_well_selection = Div(text='Well Section:', height=1) uHelper.m_well_connection = Div(text='Connection Type:', height=1) uHelper.m_well_conn_phase = Div(text='Connection Phase:', height=1) uHelper.version = Div(text='Version: 1.4.0', width=200, height=30) uHelper.version.css_classes = ["version"] #sidebar menu uHelper.spacer_1 = Spacer(width=200, height=10) uHelper.spacer_2 = Spacer(width=200, height=30) uHelper.spacer_3 = Spacer(width=200, height=30) uHelper.menu_column_1_layout = column(uHelper.spacer_3, widgetbox(uHelper.rigs_combx), widgetbox(uHelper.jobs_combx)) uHelper.menu_column_1_layout.css_classes = ["sidebarmenucombxlayout"] uHelper.well_selection_layout = column(uHelper.m_well_selection, uHelper.checkbox_group_1) uHelper.well_connection_layout = column(uHelper.m_well_connection, uHelper.checkbox_group_2) uHelper.well_conn_phase_layout = column(uHelper.m_well_conn_phase, uHelper.checkbox_group_3) uHelper.menu_column_2_layout = column(uHelper.well_selection_layout, uHelper.well_connection_layout, uHelper.well_conn_phase_layout) uHelper.menu_column_2_layout.css_classes = ["sidebarmenucheckbxlayout"] uHelper.menu_middle_layout = layout( column(uHelper.menu_column_1_layout, uHelper.menu_column_2_layout)) uHelper.menu_middle_layout.css_classes = ["sidebarmenumiddlelayout"] uHelper.menu_top_layout = layout(column(uHelper.spacer_1, uHelper.version)) uHelper.menu_top_layout.css_classes = ["sidebarmenutoplayout"] uHelper.menu_bottom_layout = layout(column(uHelper.spacer_2)) uHelper.menu_bottom_layout.css_classes = ["sidebarmenubottomlayout"] uHelper.menu_layout = layout( column(uHelper.menu_top_layout, uHelper.menu_middle_layout, uHelper.menu_bottom_layout)) uHelper.menu_layout.css_classes = ["menulayout"] #sub_plot subplot_dict = {} subplot_dict['rectcolors'] = [] subplot_dict['rectheights'] = [] subplot_dict['rectwidths'] = [] subplot_dict['text'] = [] subplot_dict['text_x'] = [] subplot_dict['text_y'] = [] subplot_dict['x'] = [] subplot_dict['y'] = [] uHelper.sub_plot_rects_source = ColumnDataSource(data=subplot_dict) # 3. plot uHelper.sub_plot = figure(x_range = [0, 60], \ y_range = [0, 30], \ plot_width = 1540, \ plot_height = 350, \ toolbar_location = None, \ sizing_mode = 'scale_both') uHelper.sub_plot.rect(x = 'x', \ y = 'y', \ width = 'rectwidths', \ height = 'rectheights', \ color = "rectcolors", \ width_units = "screen", \ height_units = "screen", \ source = uHelper.sub_plot_rects_source) rect_text = Text(x = 'text_x', \ y = 'text_y', \ text = "text", \ text_font_size = "10pt") uHelper.sub_plot.add_glyph(uHelper.sub_plot_rects_source, rect_text) uHelper.sub_plot_textbox_text = ['', '', '', ''] #leave them empty strings uHelper.sub_plot_textbox_source = ColumnDataSource(data = dict(x = [550, 550, 550, 550], \ y = [280, 250, 220, 190], \ txt = uHelper.sub_plot_textbox_text)) uHelper.sub_plot_textbox = LabelSet(x = 'x', \ y = 'y', \ x_units = 'screen', \ y_units = 'screen', \ text = 'txt', \ source = uHelper.sub_plot_textbox_source,\ text_font_size = "12pt", \ text_font_style = 'bold') uHelper.sub_plot.add_layout(uHelper.sub_plot_textbox) uHelper.sub_plot.xaxis.visible = None uHelper.sub_plot.yaxis.visible = None uHelper.sub_plot.background_fill_color = "white" uHelper.m_color_white = uHelper.sub_plot.background_fill_color uHelper.sub_plot.outline_line_color = None uHelper.sub_plot.title.align = 'center' uHelper.sub_plot.title.text_font_size = '15pt' drillingConnectionBreakdown_column = column(well_connection_chart) drillingConnectionBreakdown_column.sizing_mode = uHelper.sizing_mode drillingConnectionBreakdown_layout = layout( drillingConnectionBreakdown_column, sizing_mode=uHelper.sizing_mode) activity_type_stats_top = row(b2s_figure, line_figure, s2b_figure) uHelper.novos_config_row = row(uHelper.novos_config_plot, novos_config_table_plot) uHelper.spacer_5 = Spacer(width=uHelper.plot_width - uHelper.conn_type_comp_txtbx_offset, height=2) main_plot_column_1 = column(uHelper.main_plot, uHelper.spacer_5) main_plot_row = row(main_plot_column_1, main_textbox_plot) over_conn_analysis_column = column(uHelper.novos_config_row, main_plot_row, uHelper.sub_plot) over_conn_analysis_column.sizing_mode = uHelper.sizing_mode summary_layout = layout(column(activity_type_stats_top)) right_layout = layout(over_conn_analysis_column, sizing_mode=uHelper.sizing_mode) tabMain = Panel(title='Main', child=drillingConnectionBreakdown_layout) tabMain.tags = ["MainTag"] tabMain.name = "MainName" tabOverConnectionAnalysis = Panel(child=right_layout, title='Over Connection Analysis') tabOverConnectionAnalysis.name = "OverConnectionAnalysisName" tabOverConnectionAnalysis.tags = ["OverConnectionAnalysisTag"] uHelper.driller_vs_plot = figure(x_range=FactorRange(), \ y_range = (0, 50), \ plot_width = uHelper.plot_width - uHelper.conn_type_comp_txtbx_offset, \ plot_height = 250, \ tools = "tap, pan, box_zoom, reset",\ sizing_mode = uHelper.sizing_mode) uHelper.driller_vs_dataset, driller_vs_display_depth_list = all_main_plot.get_all_dataset( uHelper.all_connection_dict) driller_vs_display_depth_list = [ str(x) for x in driller_vs_display_depth_list ] uHelper.driller_vs_plot.toolbar.logo = None uHelper.driller_vs_plot.toolbar_location = "above" uHelper.driller_vs_plot.css_classes = ["DrillerVSPlot"] uHelper.driller_vs_plot.xaxis.ticker = mTicker uHelper.driller_vs_plot.title.align = 'center' uHelper.driller_vs_plot.legend.click_policy = "hide" uHelper.driller_vs_plot.xaxis.major_label_orientation = 1 uHelper.driller_vs_plot.x_range.factors = [] uHelper.driller_vs_plot.yaxis.axis_label = "Driller" uHelper.driller_vs_plot.axis.axis_label_text_font_style = "bold" uHelper.driller_vs_plot_source = ColumnDataSource(data=dict(HoleDepthRef = [], \ HoleDepth = [],\ B2S = [], \ S2S = [], \ S2B = [], \ Survey = [], \ BackReam = [], \ FrictionTest = [])) driller_vs_plot_vbars = uHelper.driller_vs_plot.vbar_stack(uHelper.connection_phase_list,\ x = 'HoleDepth', \ width = 0.1, \ color = uHelper.color_list, \ source = uHelper.driller_vs_plot_source, \ legend = [value(x) for x in uHelper.connection_phase_list]) uHelper.driller_vs_plot.legend.location = "top_left" uHelper.driller_vs_plot.legend.orientation = "horizontal" uHelper.driller_vs_plot.legend.border_line_width = 0 uHelper.driller_vs_plot.legend.border_line_color = "white" uHelper.driller_vs_plot.legend.border_line_alpha = 0 driller_vs_new_legend = uHelper.driller_vs_plot.legend[0] uHelper.driller_vs_plot.legend[0].plot = None uHelper.driller_vs_plot.add_layout(driller_vs_new_legend, 'above') uHelper.hybrid_vs_plot = figure(x_range = uHelper.driller_vs_plot.x_range, \ y_range = uHelper.driller_vs_plot.y_range, \ plot_width = uHelper.plot_width - uHelper.conn_type_comp_txtbx_offset, \ plot_height = 250, \ tools = "tap, pan, box_zoom, reset", \ sizing_mode = uHelper.sizing_mode) uHelper.hybrid_vs_plot.toolbar.logo = None uHelper.hybrid_vs_plot.toolbar_location = "above" uHelper.hybrid_vs_plot.css_classes = ["HybridVSPlot"] uHelper.hybrid_vs_plot.xaxis.ticker = mTicker uHelper.hybrid_vs_plot.title.align = 'center' uHelper.hybrid_vs_plot.xaxis.major_label_orientation = 1 uHelper.hybrid_vs_plot.x_range.factors = [] uHelper.hybrid_vs_plot.x_range.factors = driller_vs_display_depth_list uHelper.hybrid_vs_plot.yaxis.axis_label = "Hybrid" uHelper.hybrid_vs_plot.axis.axis_label_text_font_style = "bold" uHelper.hybrid_vs_plot_source = ColumnDataSource(data=dict(HoleDepthRef = [], \ HoleDepth = [],\ B2S = [], \ S2S = [], \ S2B = [], \ Survey = [], \ BackReam = [])) hybrid_vs_plot_vbars = uHelper.hybrid_vs_plot.vbar_stack(uHelper.connection_phase_list,\ x = 'HoleDepth', \ width = 0.1, \ color = uHelper.color_list, \ source = uHelper.hybrid_vs_plot_source) uHelper.novos_vs_plot = figure(x_range = uHelper.driller_vs_plot.x_range, \ y_range = uHelper.driller_vs_plot.y_range, \ plot_width = uHelper.plot_width - uHelper.conn_type_comp_txtbx_offset, \ plot_height = 250, \ tools = "tap, pan, box_zoom, reset", \ sizing_mode = uHelper.sizing_mode) uHelper.novos_vs_plot.css_classes = ["NovosVSPlot"] uHelper.novos_vs_plot.xaxis.ticker = mTicker uHelper.novos_vs_plot.title.align = 'center' uHelper.novos_vs_plot.xaxis.major_label_orientation = 1 uHelper.novos_vs_plot.x_range.factors = [] uHelper.novos_vs_plot.x_range.factors = driller_vs_display_depth_list uHelper.novos_vs_plot.yaxis.axis_label = "NOVOS" uHelper.novos_vs_plot.axis.axis_label_text_font_style = "bold" uHelper.novos_vs_plot_source = ColumnDataSource(data=dict(HoleDepthRef = [], \ HoleDepth = [],\ B2S = [], \ S2S = [], \ S2B = [], \ Survey = [], \ BackReam = [])) novos_vs_plot_vbars = uHelper.novos_vs_plot.vbar_stack(uHelper.connection_phase_list,\ x = 'HoleDepth', \ width = 0.1, \ color = uHelper.color_list, \ source = uHelper.novos_vs_plot_source) vs_driller_hybrid_novos_gridplot = gridplot([[uHelper.driller_vs_plot], [uHelper.hybrid_vs_plot], [uHelper.novos_vs_plot]], \ toolbar_location = "above", \ toolbar_options = dict(logo = None)) vs_driller_hybrid_novos_gridplot.sizing_mode = uHelper.sizing_mode spacer_6 = Spacer(width=uHelper.plot_width - uHelper.conn_type_comp_txtbx_offset, height=10) vs_plot_textbox_column = column(spacer_6, vs_plot_textbox) vs_plot_textbox_column.sizing_mode = uHelper.sizing_mode vs_driller_hybrid_novos_row = row(vs_driller_hybrid_novos_gridplot, vs_plot_textbox_column) vs_driller_hybrid_novos_layout = layout(vs_driller_hybrid_novos_row, sizing_mode=uHelper.sizing_mode) vsDrillerHybridNOVOS = Panel(child=vs_driller_hybrid_novos_layout, title="Driller vs Hybrid vs Novos") vsDrillerHybridNOVOS.name = "vsDrillerHybridNOVOSName" vsDrillerHybridNOVOS.tags = ["vsDrillerHybridNOVOSTag"] tabActivitytypeStats = Panel(child=summary_layout, title="Activity type Stats") tabActivitytypeStats.name = "ActivitytypeStatsName" tabActivitytypeStats.tags = ["ActivitytypeStatsTag"] p6 = figure(plot_width=uHelper.plot_width, plot_height=900, toolbar_location=None) p6.text([65, 65, 65], [65, 65, 65], text=["Coming Soon"], alpha=0.5, text_font_size="50pt", text_baseline="middle", text_align="center") p6.xaxis.visible = None p6.yaxis.visible = None p6.background_fill_color = "white" p6.outline_line_color = None tabDistributioncharts = Panel(child=p6, title="Distribution charts") tabDistributioncharts.name = "DistributionchartsName" tabDistributioncharts.tags = ["DistributionchartsTag"] about_div = Div(text="""<p> Data Visualization <br> Copyright 2018 Precision Drilling Corporation. All rights reserved.<br> Version 1.3.0(Official Build)<br> <br> <h3>Technical Support</h3> <h4>Email:</h4> <ul style="list-style-type:square"> <li>[email protected]</li> <li>[email protected]</li> </ul> <h4>Phone:</h4> <ul style="list-style-type:square"> <li>403-716-4704</li> <li>403-716-4631</li> </ul> <h4>Release Note:</h4> <ul style="list-style-type:square"> <li>--- 1.4.0 ---</li> <ul style="list-style-type:lower-alpha"> <li>Added "Friction Test" feature <br></li> <li>Linked toolbar on "Driller vs Hybrid vs Novos"<br></li> </ul> <li>--- 1.3.0 ---</li> <ul style="list-style-type:lower-alpha"> <li>Added "connection statistics" textboxes and legends <br></li> <li>Made "connection statistics" dynamically update based options from those checkboxes on the left sidebar <br></li> <li>Modified B2S and S2B UI when user clicks stackedbar on "Over Connection Analysis" <br></li> <li>Added legends on "NOVOS Config Detail" <br></li> <li>Cut off extra "Hole Depth" on x-axis ("Over Connection Times") <br></li> <li>Displyed rects if "Connection Type" is "Driller"</li> <li>Added Tooltips on stackedbar ("Over Connection Times")</li> <li>Changed "Double click to "Single Click", if user wants to hide "NOVOS Activities" </li> </ul> </ul> <ul style="list-style-type:square"> <li>--- 1.2.0 ---</li> <ul style="list-style-type:lower-alpha"> <li>Merged novos config feature <br></li> </ul> </ul> <ul style="list-style-type:square"> <li>--- 1.1.0 ---</li> <ul style="list-style-type:lower-alpha"> <li>Added "Driller vs Hybrid vs Novos" tab <br></li> <li>Moved mainplot from "Main" tab to "Over Connection Analysis" Tab</li> <li>Deleted "Continuous in Depth" and "Driller vs Novos" tabs</li> <li>"Connection Type" Checklist is greyed out, when "Driller vs Hybrid vs Novos" tab is activated</li> <li>Colors are now consistent with what we have in "PowerBI"</li> <li>"Wheel zoom" is removed from plot "tool bar"</li> <li>Display the latest dataset, whenever user clicks "Reload this page" from browser</li> </ul> </ul> </p>""", width=uHelper.plot_width, height=900) about_div.css_classes = ["aboutDiv"] tabAboutPanel = Panel(child=about_div, title="About", width=uHelper.plot_width, height=900) tabAboutPanel.name = "AboutPanelName" tabAboutPanel.tags = ["AboutPanelTag"] uHelper.tabs = Tabs(tabs = [tabMain, \ tabOverConnectionAnalysis, \ vsDrillerHybridNOVOS, \ tabActivitytypeStats, \ tabDistributioncharts, \ tabAboutPanel], width= uHelper.plot_width, sizing_mode='scale_width') uHelper.tabs.css_classes = ["tabsbackgroundcolorblack"] uHelper.spacer_4 = Spacer(width=120, height=350) uHelper.sidebar_layout = layout( column(uHelper.menu_layout, uHelper.spacer_4)) uHelper.sidebar_layout.css_classes = ["sidebarlayout"] tabs_row = row(uHelper.tabs) tabs_row.sizing_mode = uHelper.sizing_mode main_row = row(uHelper.sidebar_layout, tabs_row) main_row.sizing_mode = uHelper.sizing_mode uHelper.main_row = main_row uHelper.main_row.css_classes = ["mainrowlayout"] uHelper.main_layout = layout( uHelper.main_row, sizing_mode='scale_width') # uHelper.sizing_mode) uHelper.main_layout.css_classes = ["mainlayout"] main_plot_vbars.data_source.on_change('selected', uHelper.update_sub_plot)
def test_factor_range() -> None: s = bpp.get_scale(FactorRange(), "auto") assert isinstance(s, CategoricalScale)
def generate_plot(self): """Calculates mean and standard deviation for measure(s) by model, then generates a bar plot of model vs mean performance. TODO: Finish this doc. """ # Use this for a built-in bar plot instead, # but doesn't work with custom hover tool #p = Bar(self.data,label='modelname',values=self.measure,agg='mean',\ # title='Mean %s Performance By Model'%self.measure,legend=None,\ # tools=tools, color='modelname') #self.script,self.div = components(p) #return # TODO: hardcoded self.measure[0] for now, but should incorporate # a for loop somewhere to subplot for each selected measure # TODO: add significance information (see plot_bar_pretty # and randttest in narf_analysis) # build new pandas series of stdev values to be added to dataframe # if want to show more info on tooltip in the future, just need # to build an appropriate series to add and then build its tooltip #in the create_hover function modelnames = self.data.index.levels[0].tolist() stdev_col = pd.Series(index=modelnames) mean_col = pd.Series(index=modelnames) median_col = pd.Series(index=modelnames) n_cells_col = pd.Series(index=modelnames) #for each model, find the stdev and mean over the measure values, then #assign those values to new Series objects to use for the plot for model in modelnames: values = self.data[self.measure[0]].loc[model] stdev = values.std(skipna=True) mean = values.mean(skipna=True) median = values.median(skipna=True) if (math.isnan(stdev)) or (math.isnan(mean)) or (math.isnan(median)): # If either statistic comes out as NaN, entire column was NaN, # so model doesn't have the necessary data. continue stdev_col.at[model] = stdev mean_col.at[model] = mean median_col.at[model] = median n_cells_col.at[model] = values.count() newData = pd.DataFrame.from_dict({ 'stdev':stdev_col, 'mean':mean_col, 'median':median_col, 'n_cells':n_cells_col, }) # Drop any models with NaN values, since that means they had no # performance data for one or more columns. newData.dropna(axis=0, how='any', inplace=True) if newData.size == 0: self.script,self.div = ( "Error, no plot to display.", "None of the models contained valid performance data." ) return dat_source = ColumnDataSource(newData) tools = [ PanTool(), SaveTool(), WheelZoomTool(), ResetTool(), self.create_hover() ] xrange = FactorRange(factors=modelnames) yrange = Range1d( start=0, end=(max(newData['mean'])*1.5) ) p = figure( x_range=xrange, x_axis_label=( "Modelname, prefix: {0}, suffix: {1}" .format(self.pre, self.suf) ), y_range=yrange, y_axis_label='Mean %s'%self.measure[0], title="Mean %s Performance By Model"%self.measure[0], tools=tools, responsive=True, toolbar_location=TOOL_LOC, toolbar_sticky=TOOL_STICK, output_backend="svg" ) p.xaxis.major_label_orientation=-(np.pi/4) glyph = VBar( x='index', top='mean', bottom=0, width=VBAR_WIDTH, fill_color=VBAR_FILL, line_color='black' ) p.add_glyph(dat_source,glyph) # workaround to prevent title and toolbar from overlapping grid = gridplot( [p], ncols=GRID_COLS, responsive=True, ) self.script, self.div = components(grid)
def make_decomposed_fig(): # subplots dimensions subplot_width = plot_width subplot_height = int((float(plot_height) / len(component_names))) figs = [] # figure collection # draw multiple plots for idx in range(0, len(component_names)): # create figure if idx == 0: fig = figure( x_range=FactorRange(*data['x']), plot_height=subplot_height, plot_width=subplot_width, tools='', ) fig.xaxis.visible = True if len( component_names) == 1 else False if (0 < idx) and (idx < len(component_names) - 1): fig = figure( x_range=figs[0].x_range, plot_height=subplot_height, plot_width=subplot_width, tools='', ) fig.xaxis.visible = False elif idx == len(component_names) - 1: fig = figure( x_range=figs[0].x_range, plot_height=subplot_height, plot_width=subplot_width, tools='', ) fig.xaxis.visible = True # figure attributes setattrs(fig.xaxis, axis_line_width=1, major_label_orientation=1) setattrs(fig.x_range, range_padding=0.2) setattrs(fig.xgrid, grid_line_color='black', grid_line_alpha=0.2, grid_line_dash=[6, 4]) setattrs(fig.yaxis, axis_line_width=1, axis_label=component_names[idx], axis_label_standoff=10, axis_label_text_font_size='1em', minor_tick_line_alpha=0) setattrs(fig.y_range, start=0, range_padding=1) setattrs(fig.legend, orientation="vertical", location="top_right") setattrs(fig, outline_line_width=2, outline_line_alpha=0.1, outline_line_color="black") # toolbar tooltips = [(component_names[idx], '@{' + component_names[idx] + '}')] hover = HoverTool(tooltips=tooltips, mode='vline') wheelzoom = WheelZoomTool(dimensions='width') pan = PanTool(dimensions='width') crosshair = CrosshairTool(line_alpha=0.3) fig.add_tools(hover, wheelzoom, pan, crosshair) fig.toolbar.active_scroll = wheelzoom fig.toolbar.active_drag = pan # draw plot vbar = fig.vbar(x=dodge('x', 0.4, range=fig.x_range), top=component_names[idx], width=0.8, source=data, color=components_palette[idx]) # register this subplot into figure collection figs.append(fig) # assemble mutiple figure(subplots) into one fig_decomposed = gridplot([[fig] for fig in figs], sizing_mode='fixed', merge_tools=True, toolbar_location=None) return fig_decomposed
def make_compact_fig(): # create figure fig = figure(x_range=FactorRange(*data['x']), plot_width=plot_width, plot_height=plot_height, tools='', x_axis_label='Year-Month', y_axis_label=yaxis_label) # plot bar attributes bar_thickness = 0.8 bar_width = (float(1) / (len(component_names) + 1)) * bar_thickness bar_position = NP.array(range(0, len(component_names))) bar_position = bar_position / float(bar_position[-1] + 2) bar_position += bar_width / 2 # draw plots for idx in range(0, len(component_names)): vbar = fig.vbar(x=dodge('x', bar_position[idx], range=fig.x_range), top=component_names[idx], width=bar_width, source=data, color=components_palette[idx], legend=value(component_names[idx])) # figure attributes setattrs(fig.xaxis, axis_label_standoff=10, major_label_orientation=1) setattrs(fig.x_range, range_padding=0.2) setattrs(fig.xgrid, grid_line_color='black', grid_line_alpha=0.2, grid_line_dash=[6, 4]) setattrs(fig.yaxis, axis_label_standoff=10) setattrs(fig.y_range, start=0, range_padding=0.5) setattrs(fig.ygrid, minor_grid_line_color='black', minor_grid_line_alpha=0.05) setattrs(fig.legend, orientation='vertical', location='top_right') # toolbar # tooltips = [(stage,'@{'+stage+'}') for stage in stages] spanTags = map( lambda (project_color, project_name ): '<div><span style="color:' + project_color + ';">' + project_name + ': <b>@{' + project_name + '}</b></span></div>', zip(components_palette, component_names)) divContent = reduce(lambda accm, string: accm + string, spanTags) tooltips = '<div>' + divContent + '</div>' hover = HoverTool(tooltips=tooltips, mode='vline') wheelzoom = WheelZoomTool(dimensions='width') pan = PanTool(dimensions='width') crosshair = CrosshairTool(line_alpha=0.3) fig.add_tools(hover, wheelzoom, pan, crosshair) fig.toolbar.active_scroll = wheelzoom fig.toolbar.active_drag = pan fig.toolbar_location = None fig_compact = fig return fig_compact
def plotData_allProject_TAT(allProject_TAT_data): """ Plots median TAT data obtained in prepData_allProject_TAT() function """ # color palette projects_palette = Category20[20][0:len(stages)] # create figure fig = figure(x_range=FactorRange(*allProject_TAT_data['x'], range_padding=0.2), plot_width=plot_width, plot_height=plot_height, tools='', x_axis_label='Stages', y_axis_label='Median') # plot bar attributes bar_thickness = 1.0 bar_width = (float(1) / (len(project_names) + 1)) * bar_thickness bar_position = NP.array(range(0, len(project_names))) bar_position = bar_position - NP.median(bar_position) bar_position = bar_position / len(bar_position) / 1.2 # draw plots for idx in range(0, len(project_names)): vbar = fig.vbar(x=dodge('x', bar_position[idx], range=fig.x_range), top=project_names[idx], width=bar_width, source=allProject_TAT_data, color=projects_palette[idx], legend=value(project_names[idx])) # figure attributes setattrs(fig.xaxis, axis_label_standoff=10) setattrs(fig.xgrid, grid_line_color='black', grid_line_alpha=0.2, grid_line_dash=[6, 4]) setattrs(fig.yaxis, axis_label_standoff=10) setattrs(fig.y_range, start=0, range_padding=0.5) setattrs(fig.ygrid, minor_grid_line_color='black', minor_grid_line_alpha=0.05) setattrs(fig.legend, orientation='vertical', location='top_left') # toolbar spanTags = map( lambda (project_color, project_name ): '<div><span style="color:' + project_color + ';">' + project_name + ': <b>@{' + project_name + '}</b></span></div>', zip(projects_palette, project_names)) divContent = reduce(lambda accm, string: accm + string, spanTags) tooltips = '<div>' + divContent + '</div>' hover = HoverTool(tooltips=tooltips, mode='vline') fig.add_tools(hover) fig.toolbar_location = None return fig
#intial data: first data point as zeroes because cannot remove first glyph- perhaps a bug (each region presented is a glyph) region = ['', 'United States and Canada', 'Latin America', 'Europe, Middle East and Africa', 'Asia-Pacific'] color = ['','#6baed6','#fd8d3c', '#74c476', '#9e9ac8'] factors, params_chart = transform_inputs(DEFAULT_QTRS, DEFAULT_YRS) chart1 = PeriodAmounts(dataframe) data = {'x' : factors, '' : chart1.get_area_specific_ytd(factors, ''), 'United States and Canada' : chart1.get_area_specific_ytd(factors, 'United States and Canada'), 'Latin America' : chart1.get_area_specific_ytd(factors, 'Latin America'), 'Europe, Middle East and Africa' : chart1.get_area_specific_ytd(factors, 'Europe, Middle East and Africa'), 'Asia-Pacific' : chart1.get_area_specific_ytd(factors, 'Asia-Pacific') } #figure set p = figure(x_range=FactorRange(*factors), plot_height=350, plot_width=1000, title='Netflix Revenue, YTD (stacked)', toolbar_location=None, tools="hover", tooltips="$name @x: @$name") #starting glyphs p.vbar_stack(region, x='x', width=0.9, color=color, source=data, legend_label = region) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.axis.minor_tick_line_color = None p.outline_line_color = None p.add_layout(p.legend[0], 'right')
def budgeting_graph(df, current_date, conn): cur = conn.cursor() sel_date = current_date cur.execute("select * from budgeting where period = '{}'".format(sel_date)) results = cur.fetchall() df_selected = df[df['YearMonth'] == sel_date] period_cats = sorted(df_selected['category'].unique().tolist()) budget_categories = [] for i in period_cats: index = 0 for j in results: if i == j[2]: budget_categories.append(j[3]) index += 1 if index < 1: budget_categories.append(0) else: pass ym = df_selected.groupby('category', as_index=False)['actual_amount'].sum() df_aa = ym['actual_amount'].tolist() new_dict = {} new_dict['Budget'] = budget_categories new_dict['Actual'] = df_aa new_labels = ['Budget', 'Actuals'] counts = sum(zip(new_dict['Budget'], new_dict['Actual']), ()) x = [(category, label1) for category in period_cats for label1 in new_labels] source = ColumnDataSource(data=dict(x=x, counts=counts)) p = figure(x_range=FactorRange(*x), plot_height=600, plot_width=700, title="Budgets vs Actuals", toolbar_location=None, tools="hover", tooltips="@x : @$name") p.vbar(x='x', top='counts', width=0.9, source=source, line_color="white", fill_color=factor_cmap('x', palette=Spectral5, factors=new_labels, start=1, end=2), name="counts") p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xaxis.major_label_orientation = 1 p.xaxis.group_label_orientation = 'vertical' p.xgrid.grid_line_color = None return p
def reports(): default=None script=None div=None employees=User.query.filter(User.id>0).order_by(User.last_name).all() schools=School.query.order_by(School.school_name).all() if request.method=='POST': school=request.form.get('school') employee=request.form.get('employee') if school: event_query=Event.query.filter_by(school=school).order_by(Event.complete_timestamp) df=pd.read_sql(event_query.statement, event_query.session.bind) df_group=df.groupby(['event_type']).agg({'event_type' : 'count'}); df_group.columns=['count'] df_group=df_group.reset_index() factors=df['event_type'].unique().tolist() q=figure(plot_height=350, title="Events in {}".format(school), toolbar_location="right", x_range=FactorRange(*factors)) q.vbar(x='event_type', top='count', source=df_group, width=0.5) script, div = components(q) return render_template('report.html', default=default, user=current_user, employees=employees, schools=schools, script=script, div=div) elif employee: event_query=Event.query.filter_by(person_completed=employee).order_by(Event.complete_timestamp) df=pd.read_sql(event_query.statement, event_query.session.bind) df_group=df.groupby(['event_type']).agg({'event_type' : 'count'}); df_group.columns=['count'] df_group=df_group.reset_index() factors=df['event_type'].unique().tolist() employee_name=User.query.filter_by(employee_id=employee).first() q=figure(plot_height=350, title="Events by {}".format(employee_name.full_name), toolbar_location="right", x_range=FactorRange(*factors)) q.vbar(x='event_type', top='count', source=df_group, width=0.5) script, div = components(q) return render_template('report.html', default=default, user=current_user, employees=employees, schools=schools, script=script, div=div) else: pass event_query=Event.query.order_by(Event.complete_timestamp) df=pd.read_sql(event_query.statement, event_query.session.bind) df_group=df.groupby(['event_type']).agg({'event_type' : 'count'}); df_group.columns=['count'] df_group=df_group.reset_index() df_group['color']=Category20c[df_group.shape[0]] df_group['angle']=df_group['count']/df_group['count'].sum()*2*pi df_group['percent']=np.round((df_group['count']/df_group['count'].sum()*100)) p = figure(plot_height=350, title="Events in District", toolbar_location="right", tools="hover", tooltips="@event_type: @count events, @percent percent", x_range=(-1, 2.0)) p.wedge(x=0.5, y=1, radius=0.75, start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), line_color="green", fill_color='color', legend_field='event_type', source=df_group) '''df_group["percent"] = df_group['percent'].astype(str) df_group['percent'] = df_group['percent'].str.pad(35, side = "left") source=ColumnDataSource(df_group) labels = LabelSet(x=0.5, y=1, text='percent', text_align='center', text_color='white', angle=cumsum('angle', include_zero=True), source=source, render_mode='canvas') p.add_layout(labels)''' p.axis.axis_label=None p.axis.visible=False p.grid.grid_line_color = None script, div = components(p) return render_template('report.html', default=default, user=current_user, employees=employees, schools=schools, script=script, div=div)
def render_hist(df: pd.DataFrame, x: str, meta: ColumnMetadata, plot_width: int, plot_height: int) -> Figure: """ Render a histogram """ if is_categorical(meta["dtype"]): tooltips = [ (x, "@x"), ("Count", "@count"), ("Label", "@label"), ] else: df = df.copy() df["repr"] = [ f"[{row.lower_bound:.0f}~{row.upper_bound:.0f})" for row in df.itertuples() ] tooltips = [ (x, "@repr"), ("Frequency", "@count"), ("Label", "@label"), ] cmapper = CategoricalColorMapper(palette=Category10[3], factors=LABELS) if is_categorical(df["x"].dtype): radius = 0.99 x_range = FactorRange(*df["x"].unique()) else: radius = df["x"][1] - df["x"][0] x_range = Range1d(df["x"].min() - radius, df["x"].max() + radius) y_range = Range1d(0, df["count"].max() * 1.05) fig = tweak_figure( Figure( x_range=x_range, y_range=y_range, plot_width=plot_width, plot_height=plot_height, tools="hover", toolbar_location=None, tooltips=tooltips, )) fig.vbar( x="x", width=radius, top="count", source=df, fill_alpha=0.3, color={ "field": "label", "transform": cmapper }, legend_field="label", ) relocate_legend(fig, "right") return fig
def get_exptype_counts(exposures, calibs, width=300, height=300, min_border_left=50, min_border_right=50): """ Generate a horizontal bar plot showing the counts for each type of exposure grouped by whether they have FLAVOR='science' or PROGRAM='calib' ARGS: exposures : a table of exposures which only contain those with FLAVOR='science' calibs : a table of exposures which only contains those with PROGRAm='calibs' Options: height, width: height and width in pixels min_border_left, min_border_right = set minimum width of surrounding labels (in pixels) """ darks = len(exposures[exposures['PROGRAM'] == 'DARK']) grays = len(exposures[exposures['PROGRAM'] == 'GRAY']) brights = len(exposures[exposures['PROGRAM'] == 'BRIGHT']) arcs = len(calibs['arc' in calibs['FLAVOR']]) flats = len(calibs['flat' in calibs['FLAVOR']]) zeroes = len(calibs['zero' in calibs['FLAVOR']]) types = [('calib', 'ZERO'), ('calib', 'FLAT'), ('calib', 'ARC'), ('science', 'BRIGHT'), ('science', 'GRAY'), ('science', 'DARK')] counts = np.array([zeroes, flats, arcs, brights, grays, darks]) COLORS = ['tan', 'orange', 'yellow', 'green', 'blue', 'red'] src = ColumnDataSource({'types': types, 'counts': counts}) p = bk.figure(width=width, height=height, x_range=(0, np.max(counts) * 1.15), y_range=FactorRange(*types), title='Exposure Type Counts', toolbar_location=None, min_border_left=min_border_left, min_border_right=min_border_right) p.hbar(y='types', right='counts', left=0, height=0.5, line_color='white', fill_color=factor_cmap('types', palette=COLORS, factors=types), source=src) labels = LabelSet(x='counts', y='types', text='counts', level='glyph', source=src, render_mode='canvas', x_offset=5, y_offset=-7, text_color='gray', text_font='tahoma', text_font_size='8pt') p.add_layout(labels) p.ygrid.grid_line_color = None p.xaxis.axis_label = 'label' p.xaxis.axis_label_text_color = '#ffffff' return p
df = df.melt(id_vars=["Features"], var_name=["Tool"]) df['Tool'] = pd.Categorical(df['Tool'], tool_list) df["Features"] = pd.Categorical( df["Features"], df["Features"].drop_duplicates(keep="first").tolist()) df["value"].replace(0, nan, inplace=True) df = df.loc[~df.value.isnull()] categories = categories[["Features", "Category", "Definition"]] df = df.merge(categories, how="left", on=["Features"]) y_range = FactorRange(factors=[ i for i in df.sort_values(by="Category") [["Category", "Features"]].drop_duplicates().values.tolist()[::-1] ]) x_range = FactorRange(factors=df["Tool"].drop_duplicates().tolist()) choose_color = 0 for c in df.sort_values(by="Category")["Category"].drop_duplicates().tolist(): df.loc[df.Category == c, "color"] = palette[choose_color] choose_color += 1 source = ColumnDataSource( data=dict(tool=df["Tool"].tolist(), feature=df[["Category", "Features"]].values.tolist(), color=df["color"].tolist(), category=df["Category"].tolist(), desc=df["Definition"].tolist()))
def test__get_scale_factor_range(): s = bph._get_scale(FactorRange(), "auto") assert isinstance(s, CategoricalScale)
def test_init_with_keyword_arguments(self) -> None: factor_range = FactorRange(factors=["a", "b", "c", "d", "e"]) assert factor_range.factors == ["a", "b", "c", "d", "e"]
'fruits': fruits, '2015': [2, 1, 4, 3, 2, 4], '2016': [5, 3, 3, 2, 4, 6], '2017': [3, 2, 4, 4, 5, 3] } palette = ["#c9d9d3", "#718dbf", "#e84d60"] # this creates [ ("Apples", "2015"), ("Apples", "2016"), ("Apples", "2017"), ("Pears", "2015), ... ] x = [(fruit, year) for fruit in fruits for year in years] counts = sum(zip(data['2015'], data['2016'], data['2017']), ()) # like an hstack source = ColumnDataSource(data=dict(x=x, counts=counts)) p = figure(x_range=FactorRange(*x), plot_height=350, title="Fruit Counts by Year", toolbar_location=None, tools="") p.vbar(x='x', top='counts', width=0.9, source=source, line_color="white", fill_color=factor_cmap('x', palette=palette, factors=years, start=1, end=2))
def test_cannot_initialize_with_both_keyword_and_positional_arguments(self) -> None: with pytest.raises(ValueError): FactorRange(["a", "b", "c"], factors=["a", "b", "c"])
#names = ["Delfstoffenwinning", "Energievoorziening", "Hout- en bouwmaterialenindustrie", "Metalektro", "Meubelindustrie", "Papier- en grafische industrie", "Raffinaderijen en chemie", "Textielindustrie", "Voedings-, genotmiddelenindustrie", "Waterbedrijven en afvalbeheer", "Overige industrie", "Industrie"] names = [ "Delfstoffen", "Energie", "Bouw", "Metalektro", "Meubels", "Papier", "chemie", "Textiel", "Voeding", "Water", "Overige", "Industrie" ] # In[19]: output_file("colormapped_bars.html") source = ColumnDataSource( data=dict(branches=ub, values=vList, color=color, names=names)) hover = HoverTool(tooltips=[("Industrie", "@names"), ("Aandeel", "@values")]) p = figure(x_range=FactorRange(factors=ub), y_range=(0.00, 40.00), plot_height=250, title="Precentages weging tov totaal", toolbar_location=None, tools=[hover]) p.vbar(x='branches', top='values', width=0.9, color='color', source=source) p.xgrid.grid_line_color = None p.legend.orientation = "horizontal" p.legend.location = "top_center" show(p) # #### newDF contains feature "weging_tov_b" in percentages
p_3.vbar(x='t_d', top='P_i_efec', source=source_scs, color='black', fill_color=Spectral4[0], fill_alpha=0.6, width=20, legend_label='Precipitación Efectiva') p_3.background_fill_color = 'lightblue' p_3.background_fill_alpha = 0.20 #Plot n-k p_4 = figure(plot_width=500, plot_height=500, x_range=FactorRange(*x), y_axis_label='[N° de embalses] / [horas]', title='4. Estimación de parámetros') p_4.vbar(x='x', top='counts', width=0.2, source=source_nk, fill_color='yellow', fill_alpha=0.5, color='black') p_4.background_fill_color = 'lightblue' p_4.background_fill_alpha = 0.20 # Plot HUI
def plot_multiple_categorical_bar_chart_distribution( df: pd.DataFrame, col_name: str, group_category: str, vars_to_drop: list = [], plot_width: int = 330, plot_height: int = 330, colours: list = ["#8c9eff", "#536dfe"]): """ :param df: dataframe with the bar charts that will be plotted :param col_name: column name for the y values of the graph as bar charts :param group_category: column name where the categorical data is :param vars_to_drop: values to be dropped if needed :param plot_width: width of the plot :param plot_height: height of the plot :param colours: colours used for the fill of each bar chart variable :return: """ grouped_table = df.groupby([group_category, col_name]).size() / df.groupby( [group_category]).size() if len(vars_to_drop) > 0: grouped_table = grouped_table.drop(vars_to_drop) grouped_df = pd.DataFrame(grouped_table) grouped_df = grouped_df.rename(columns={0: "category"}).reset_index() index_tuple = [(col_cat, group_cat) for col_cat in grouped_df[col_name].unique() for group_cat in grouped_df[group_category].unique()] percentages = [] for tuple_ in index_tuple: col_cat = tuple_[0] group_cat = tuple_[1] per = grouped_df[(grouped_df[group_category] == group_cat) & (grouped_df[col_name] == col_cat)]["category"] percentages.append(per) percentages = tuple(percentages) colour_combinations = int(len(index_tuple) / 2) fill_colours = colours * colour_combinations source = ColumnDataSource(data=dict( x=index_tuple, percentages=percentages, fill_colours=fill_colours)) p = figure(x_range=FactorRange(*index_tuple), plot_height=plot_height, plot_width=plot_width, title="Distribution of " + col_name + " by " + group_category, toolbar_location=None, tools="save, hover") p.vbar(x='x', top='percentages', color='fill_colours', width=0.9, source=source) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xaxis.major_label_orientation = 1 p.xgrid.grid_line_color = None p.yaxis[0].formatter = NumeralTickFormatter(format='0%') tooltips = [("variable", "@x"), ('percentage', "@percentages" + '{0%}')] hover = p.select(dict(type=HoverTool)) hover.tooltips = tooltips return p
("Q3", "aug"), ("Q3", "sep"), ("Q4", "oct"), ("Q4", "nov"), ("Q4", "dec"), ] regions = ['east', 'west'] source = ColumnDataSource(data=dict( x=factors, east=[5, 5, 6, 5, 5, 4, 5, 6, 7, 8, 6, 9], west=[5, 7, 9, 4, 5, 4, 7, 7, 7, 6, 6, 7], )) p = figure(x_range=FactorRange(*factors), plot_height=250, toolbar_location=None, tools="") p.vbar_stack(regions, x='x', width=0.9, alpha=0.5, color=["blue", "red"], source=source, legend=[value(x) for x in regions]) p.y_range.start = 0 p.y_range.end = 18 p.x_range.range_padding = 0.1
def test__check_compatible_scale_and_ranges_compat_factor() -> None: plot = Plot(x_scale=CategoricalScale(), x_range=FactorRange()) check = plot._check_compatible_scale_and_ranges() assert check == []
("DimGray", "#696969", "Gray/Black"), ("LightSlateGray", "#778899", "Gray/Black"), ("SlateGray", "#708090", "Gray/Black"), ("DarkSlateGray", "#2F4F4F", "Gray/Black"), ("Black", "#000000", "Gray/Black"), ], columns=["Name", "Color", "Group"]) source = ColumnDataSource( dict( names=list(css3_colors.Name), groups=list(css3_colors.Group), colors=list(css3_colors.Color), )) xdr = FactorRange(factors=list(css3_colors.Group.unique())) ydr = FactorRange(factors=list(reversed(css3_colors.Name))) plot = Plot(title="CSS3 Color Names", x_range=xdr, y_range=ydr, plot_width=600, plot_height=2000) rect = Rect(x="groups", y="names", width=1, height=1, fill_color="colors", line_color=None) rect_renderer = plot.add_glyph(source, rect)
def test_get_set_multi_mismatch(self) -> None: obj = bmp._list_attr_splat([LinearAxis(), FactorRange()]) with pytest.raises(AttributeError) as e: obj.formatter.power_limit_low == 10 assert str(e.value).endswith("list items have no %r attribute" % "formatter")
def make_axis(axis, size, factors, dim, flip=False, rotation=0, label_size=None, tick_size=None, axis_height=35): factors = list(map(dim.pprint_value, factors)) nchars = np.max([len(f) for f in factors]) ranges = FactorRange(factors=factors) ranges2 = Range1d(start=0, end=1) axis_label = dim_axis_label(dim) reset = "range.setv({start: 0, end: range.factors.length})" ranges.callback = CustomJS(args=dict(range=ranges), code=reset) axis_props = {} if label_size: axis_props['axis_label_text_font_size'] = value(label_size) if tick_size: axis_props['major_label_text_font_size'] = value(tick_size) tick_px = font_size_to_pixels(tick_size) if tick_px is None: tick_px = 8 label_px = font_size_to_pixels(label_size) if label_px is None: label_px = 10 rotation = np.radians(rotation) if axis == 'x': align = 'center' # Adjust height to compensate for label rotation height = int(axis_height + np.abs(np.sin(rotation)) * ((nchars*tick_px)*0.82)) + tick_px + label_px opts = dict(x_axis_type='auto', x_axis_label=axis_label, x_range=ranges, y_range=ranges2, plot_height=height, plot_width=size) else: # Adjust width to compensate for label rotation align = 'left' if flip else 'right' width = int(axis_height + np.abs(np.cos(rotation)) * ((nchars*tick_px)*0.82)) + tick_px + label_px opts = dict(y_axis_label=axis_label, x_range=ranges2, y_range=ranges, plot_width=width, plot_height=size) p = Figure(toolbar_location=None, tools=[], **opts) p.outline_line_alpha = 0 p.grid.grid_line_alpha = 0 if axis == 'x': p.yaxis.visible = False axis = p.xaxis[0] if flip: p.above = p.below p.below = [] p.xaxis[:] = p.above else: p.xaxis.visible = False axis = p.yaxis[0] if flip: p.right = p.left p.left = [] p.yaxis[:] = p.right axis.major_label_orientation = rotation axis.major_label_text_align = align axis.major_label_text_baseline = 'middle' axis.update(**axis_props) return p