def after_write_file(self, args, filename, doc): ''' ''' if args.show: from bokeh.util.browser import view view(filename)
def show(self, app_path, browser=None, new='tab'): ''' Opens an app in a browser window or tab. Useful for testing server applications on your local desktop but should not call when running bokeh-server on an actual server. Args: app_path (str) : the app path to open The part of the URL after the hostname:port, with leading slash. browser (str, optional) : browser to show with (default: None) For systems that support it, the **browser** argument allows specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default" (see the ``webbrowser`` module documentation in the standard lib for more details). new (str, optional) : window or tab (default: "tab") If ``new`` is 'tab', then opens a new tab. If ``new`` is 'window', then opens a new window. Returns: None ''' if not app_path.startswith("/"): raise ValueError("app_path must start with a /") from bokeh.util.browser import view url = "http://localhost:%d%s%s" % (self.port, self.prefix, app_path) view(url, browser=browser, new=new)
def main(): p = argparse.ArgumentParser() p.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin) p.add_argument('outfile', nargs='?', default="site/index.html") p.add_argument('-t', '--template', default='template.jinja', help="""Jinja2 Tempate file[default: %(default)]""") p.add_argument('-v', '--view', default=False, help="""Launch browser to view output: %(default)]""") a = p.parse_args() df = pd.read_csv(a.infile) plots = mkplots(df) script, div = components(plots) js_resources = CDN.render_js() css_resources = CDN.render_css() env = Environment(loader=FileSystemLoader(THIS_DIR), trim_blocks=True) # Alias str.format to strformat in template env.filters['strformat'] = str.format template = env.get_template(a.template) html = template.render( date=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), command=" ".join(sys.argv), workdir=os.getcwd(), user=getpass.getuser(), title="Santa Performance Plots", js_resources=js_resources, css_resources=css_resources, script=script, div=div) with open(a.outfile, "w") as f: f.write(html.encode('utf-8')) # to deploy to gh-pages, use the function `gh=deploy` defined in ~.bash_profile # first copy index.html tp the `site/` directory # Cribbed from https://gist.github.com/cobyism/4730490 # git subtree push --prefix site origin gh-pages if a.view: view(a.outfile)
def show(self, app_path, browser=None, new='tab'): ''' Opens an app in a browser window or tab. This method is useful for testing or running Bokeh server applications on a local machine but should not call when running Bokeh server for an actual deployment. Args: app_path (str) : the app path to open The part of the URL after the hostname:port, with leading slash. browser (str, optional) : browser to show with (default: None) For systems that support it, the **browser** argument allows specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default" (see the ``webbrowser`` module documentation in the standard lib for more details). new (str, optional) : window or tab (default: "tab") If ``new`` is 'tab', then opens a new tab. If ``new`` is 'window', then opens a new window. Returns: None ''' if not app_path.startswith("/"): raise ValueError("app_path must start with a /") address_string = 'localhost' if self.address is not None and self.address != '': address_string = self.address url = "http://%s:%d%s%s" % (address_string, self.port, self.prefix, app_path) from bokeh.util.browser import view view(url, browser=browser, new=new)
def show(self): """Display a figure (called by backtrader).""" # as the plot() function only created the figures and the columndatasources with no data -> now we fill it for idx in range(len(self.figurepages)): model = self.generate_model(idx) if self.p.output_mode in ['show', 'save']: if self._iplot: css = self._output_stylesheet() display(HTML(css)) show(model) else: filename = self._output_plot_file(model, idx, self.p.filename) if self.p.output_mode == 'show': view(filename) elif self.p.output_mode == 'memory': pass else: raise RuntimeError( f'Invalid parameter "output_mode" with value: {self.p.output_mode}' ) self._reset()
widgets = Column(children=[ Row(children=[ Column(children=[ click_button, disabled_button, toggle, dropdown, dropdown_split, checkbox_group, radio_group, checkbox_button_group, radio_button_group, ]), Column(children=[ text_input, autocomplete_input, select, multi_select, slider, range_slider, date_slider, date_range_slider, spinner, color_picker, date_picker, paragraph, div, pre_text, ]), tabs, ]), table, ]) doc = Document() doc.add_root(widgets) if __name__ == "__main__": doc.validate() filename = "widgets.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Widgets")) print("Wrote %s" % filename) view(filename)
def plot_selected_country(self, name, output, module="bokeh"): if self.selected is None: raise ValueError("no country selected") # create dictionary out of df that can be put into JS function grouped_df_d = self.df_daily.groupby("Country/Region", sort=False) grouped_df_t = self.df_total.groupby("Country/Region", sort=False) grouped_list_d = grouped_df_d.apply(lambda x: x.to_dict(orient="list")) grouped_list_t = grouped_df_t.apply(lambda x: x.to_dict(orient="list")) df_dict_nested_d = grouped_list_d.to_dict() df_dict_nested_t = grouped_list_t.to_dict() df_dict_daily = {} df_dict_total = {} keys_to_ignore = ["Province/State", "Country/Region", "Lat", "Long"] for key, value in df_dict_nested_d.items(): helper_list = [] for key_two, value_two in value.items(): if key_two in keys_to_ignore: continue else: # sums up countries that occur multiple times helper_list.append(sum(value_two)) df_dict_daily[key] = helper_list for key, value in df_dict_nested_t.items(): helper_list = [] for key_two, value_two in value.items(): if key_two in keys_to_ignore: continue else: # sums up countries that occur multiple times helper_list.append(sum(value_two)) df_dict_total[key] = helper_list dates = [] dates_str = [] for date_str in self.selected.index: date_obj = datetime.strptime(date_str, '%m/%d/%y') dates.append(date_obj) date_str_new = datetime.strptime(date_str, '%m/%d/%y').strftime('%d %b %Y') dates_str.append(date_str_new) df_dict_daily["dates"] = dates df_dict_total["dates"] = dates df_dict_daily["dates_str"] = dates_str df_dict_total["dates_str"] = dates_str if module == "bokeh": # also necessary to make it compatible with JS function df_dict_daily["selected"] = df_dict_daily[name] df_dict_total["selected"] = df_dict_total[name] source_daily = ColumnDataSource(data=df_dict_daily) source_total = ColumnDataSource(data=df_dict_total) # create two plots XAXIS_LABEL = "Date" YAXIS_LABEL = "Death Cases" LEGEND_LOC = "top_left" TOOLTIPS = [("Date", "@dates_str"), ("Cases of selected country", "@selected"), ("Cases worldwide", "@World")] TOOLS = [ HoverTool(tooltips=TOOLTIPS), "pan", "wheel_zoom", "box_zoom", "reset" ] HEIGHT = 600 WIDTH = 760 SIZE = 1 CIRCLE_SIZE = 12 colors = ["lightgray", "red"] pd = figure(x_axis_type="datetime", title="Daily Infections", plot_height=HEIGHT, tools=TOOLS, width=WIDTH, css_classes=["we-need-this-for-manip"], name="d_infections") pt = figure(x_axis_type="datetime", title="Total Infections", plot_height=HEIGHT, tools=TOOLS, width=WIDTH, css_classes=["we-need-this-for-manip-total"], name="t_infections") # pd.vbar(x='dates', top="World", color=colors[0], line_width=SIZE, # source=source_daily, legend_label="Worldwide") pd.vbar(x='dates', top="selected", color=colors[1], line_width=SIZE, source=source_daily, legend_label="Selected Country") # HoverTool does not work for vbar so invisible circles are necessary # pd.circle(x='dates', y="World", color=colors[0], size=CIRCLE_SIZE, # source=source_daily, legend_label="Worldwide", fill_alpha=0, # line_alpha=0) pd.circle(x='dates', y="selected", color=colors[1], size=CIRCLE_SIZE, source=source_daily, legend_label="Selected Country", fill_alpha=0, line_alpha=0) pd.legend.location = LEGEND_LOC pd.yaxis.axis_label = YAXIS_LABEL pd.xaxis.axis_label = XAXIS_LABEL # pt.vbar(x='dates', top="World", color=colors[0], line_width=SIZE, # source=source_total, legend_label="Worldwide") pt.vbar(x='dates', top="selected", color=colors[1], line_width=SIZE, source=source_total, legend_label="Selected Country") # pt.circle(x='dates', y="World", color=colors[0], size=CIRCLE_SIZE, # source=source_total, legend_label="Worldwide", fill_alpha=0, # line_alpha=0) pt.circle(x='dates', y="selected", color=colors[1], size=CIRCLE_SIZE, source=source_total, legend_label="Selected Country", fill_alpha=0, line_alpha=0) pt.legend.location = LEGEND_LOC pt.yaxis.axis_label = YAXIS_LABEL pt.xaxis.axis_label = XAXIS_LABEL output_file(output) # dropdown menu # dates can't be sorted like this, so it has to be removed for this step df_dict_total.pop("dates") df_dict_total.pop("dates_str") sort_options = sorted(df_dict_total.items(), key=lambda x: x[1][-1], reverse=True) options = [] for tpl in sort_options: total_cases_list = list(str(tpl[1][-1])) total_cases_str_sep = "" for i, num in enumerate(total_cases_list): total_cases_str_sep += num if i == len(total_cases_list) - 1: continue elif len(total_cases_list) % 3 == 0: if i % 3 == 2: total_cases_str_sep += "," elif len(total_cases_list) % 3 == 1: if i % 3 == 0: total_cases_str_sep += "," elif len(total_cases_list) % 3 == 2: if i % 3 == 1: total_cases_str_sep += "," if tpl[0] == name: selected_total_cases_sep = total_cases_str_sep options.append(f"{tpl[0]}: {total_cases_str_sep} total cases") options.remove(f"selected: {selected_total_cases_sep} total cases") df_dict_total["dates"] = dates df_dict_total["dates_str"] = dates_str select = Select( title="Select a country", value=f"{name}: {selected_total_cases_sep} total cases", options=options, sizing_mode="scale_width") with open("main.js", "r") as f: select.js_on_change( "value", CustomJS(args=dict( source_d=source_daily, source_t=source_total, df_dict_t=df_dict_total, df_dict_d=df_dict_daily, ), code=f.read())) plots = column(pd, pt) # show(column(select, plots)) with open("template.html", "r") as f: template = f.read() save(column(select, plots), template=template) view(output) if module == "mpl": confirmed_cases = [] confirmed_cases_world = [] # cave: only for daily for sub_arr in self.selected.values: confirmed_cases.append(sub_arr[0]) for sub_arr in self.world_data_daily.values: confirmed_cases_world.append(sub_arr[0]) fig, ax = plt.subplots() date_format = DateFormatter("%d %b %Y") world_plot = ax.bar(dates, confirmed_cases_world, bottom=0, color="lightgray") country_plot = ax.bar(dates, confirmed_cases, bottom=0) ax.set(xlabel="Date", ylabel="Death Cases") ax.xaxis.set_major_formatter(date_format) fig.subplots_adjust(bottom=0.175) plt.xticks(rotation=35, fontsize=7) plt.legend((world_plot[0], country_plot[0]), ("Worldwide", "{}".format(name))) plt.show()
def writeMapToFile(filename, doc): with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Google Maps Example")) print "Wrote %s" % filename view(filename)
def test_view_bad_new() -> None: with pytest.raises(RuntimeError) as e: bub.view("foo", new="junk") assert str( e ) == "invalid 'new' value passed to view: 'junk', valid values are: 'same', 'window', or 'tab'"
def test_view_args(): db = bub.DummyWebBrowser bub.DummyWebBrowser = _RecordingWebBrowser # test http locations used as-is bub.view("http://foo", browser="none") assert _open_args == (('http://foo',), {'autoraise': True, 'new': 0}) # test non-http locations treated as local files bub.view("/foo/bar", browser="none") assert _open_args == (('file:///foo/bar',), {'autoraise': True, 'new': 0}) # test autoraise passed to open bub.view("http://foo", browser="none", autoraise=False) assert _open_args == (('http://foo',), {'autoraise': False, 'new': 0}) # test handling of new values bub.view("http://foo", browser="none", new="same") assert _open_args == (('http://foo',), {'autoraise': True, 'new': 0}) bub.view("http://foo", browser="none", new="window") assert _open_args == (('http://foo',), {'autoraise': True, 'new': 1}) bub.view("http://foo", browser="none", new="tab") assert _open_args == (('http://foo',), {'autoraise': True, 'new': 2}) bub.DummyWebBrowser = db
def stop(PORT=EOD_HOSE_LISTEN_PORT): view(f"http://localhost:{PORT}/shutdown")
def intplotter(data, isodata, nodata, y, hetclassintdf): linewidth = 1.5 source = ColumnDataSource(data) s2 = ColumnDataSource(data=dict(mz=data["mz"], Error=data["Error"], RA=data["RA"], Formula=data["Formula"], HeteroClass=data["HeteroClass"])) isosource = ColumnDataSource(isodata) nosource = ColumnDataSource(nodata) url = "http://www.chemspider.com/Search.aspx?q=@Formula" TOOLS = "crosshair,pan,wheel_zoom,box_zoom,reset,tap,save,box_select,poly_select,lasso_select,hover" figdims = (900, 500) #pixel dimensions for the normal figures msxlim = [200, 700] #x limits in m/z for the mass spectra vkxlim = [0, 1] vkylim = [0, 2] p1 = figure(tools=TOOLS, title=y[:-9] + " - Van Krevelen", width=figdims[0], height=figdims[1], x_axis_label='O/C', y_axis_label='H/C', x_range=vkxlim, y_range=vkylim) color_mapper = LinearColorMapper(palette=glocmap, low=msxlim[0], high=msxlim[1]) p1.scatter(x='OC', y='HC', source=source, size='VKsize', fill_color={ 'field': 'mz', 'transform': color_mapper }, fill_alpha=0.75, line_color=None) #use size not radius. hover = p1.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([('Formula', "@Formula"), ('Mass', "@mz{1.11111}"), ('Error (ppm)', "@Error{1.11}")]) taptool = p1.select(type=TapTool) taptool.callback = OpenURL(url=url) color_bar = ColorBar(color_mapper=color_mapper, title="m/z", border_line_color=None, location=(0, 0), scale_alpha=0.7) #orientation='horizontal',location='top_left', scale_alpha=0.7)#,ticker=FixedTicker(ticks=[2,6,10,14,18])) p1.add_layout(color_bar, "right") dbexlim = [0, 45] dbeylim = [0, 40] cmax = max(data["O"]) cmax = int(5 * round(float(cmax) / 5)) p2 = figure(tools=TOOLS, title=y[:-9] + " - DBE vs C# Plot", width=figdims[0], height=figdims[1], x_axis_label='C#', y_axis_label='DBE', x_range=dbexlim, y_range=dbeylim) color_mapper2 = LinearColorMapper(palette=glocmap2, low=0, high=cmax) p2.scatter(x='C', y='DBE', source=source, size='VKsize', fill_color={ 'field': 'O', 'transform': color_mapper2 }, fill_alpha=0.75, line_color=None) hover = p2.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([('Formula', "@Formula"), ('Mass', "@mz{1.11111}"), ('Error (ppm)', "@Error{1.11}")]) taptool = p2.select(type=TapTool) taptool.callback = OpenURL(url=url) color_bar2 = ColorBar( color_mapper=color_mapper2, title="O#", border_line_color=None, location=(0, 0), scale_alpha=0.7, ticker=FixedTicker( ticks=[0, int(cmax / 4), int(cmax / 2), int(3 * cmax / 4), cmax])) p2.add_layout(color_bar2, "right") aixlim = [0, 45] aiylim = [0, 1] p3 = figure(tools=TOOLS, title=y[:-9] + " - AI(mod) vs C# Plot", width=figdims[0], height=figdims[1], x_axis_label='C#', y_axis_label='AI(mod)', x_range=aixlim, y_range=aiylim) color_mapper3 = LinearColorMapper(palette=glocmap2, low=0, high=cmax) p3.scatter(x='C', y='AImod', source=source, size='VKsize', fill_color={ 'field': 'O', 'transform': color_mapper3 }, fill_alpha=0.75, line_color=None) hover = p3.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([('Formula', "@Formula"), ('Mass', "@mz{1.11111}"), ('Error (ppm)', "@Error{1.11}")]) taptool = p3.select(type=TapTool) taptool.callback = OpenURL(url=url) color_bar3 = ColorBar( color_mapper=color_mapper3, title="O#", border_line_color=None, location=(0, 0), scale_alpha=0.7, ticker=FixedTicker( ticks=[0, int(cmax / 4), int(cmax / 2), int(3 * cmax / 4), cmax])) #orientation='horizontal',location='top_left', scale_alpha=0.7)#,ticker=FixedTicker(ticks=[2,6,10,14,18])) p3.add_layout(color_bar3, "right") p4 = figure(tools=TOOLS, title=y[:-9] + " - Assigned Centroid MS", width=figdims[0], height=figdims[1], x_axis_label='m/z', y_axis_label='Abundance', y_range=[min(data["RA"]), max(data["RA"])], x_range=msxlim) p4.segment(x0=0, x1=800, y0=0, y1=0, line_width=1, line_color="black") p4.segment(x0='mz', y0=0, x1='mz', y1='RA', source=source, line_width=linewidth, line_color="black") p4.scatter(x='mz', y='RA', source=source, fill_color='black', line_color=None) hover = p4.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([('Formula', "@Formula"), ('Mass', "@mz{1.11111}"), ('Error (ppm)', "@Error{1.11}")]) taptool = p4.select(type=TapTool) taptool.callback = OpenURL(url=url) p4.yaxis[0].formatter = PrintfTickFormatter(format="%4.1e") """ #this is me trying to plot a barplot of heteroatomic class distributions... p7 = figure(tools=TOOLS, title=y[:-9]+"",width=800, height=600, x_axis_label='HeteroClass',y_axis_label='Count',webgl=True) p7.quad(left="HetClassInts",y=hetclassdf[0],source=source,width=5,height=) t7 = layouts.Column(hist) tab7 = Panel(child=t7,title="test") """ stretch = msxlim[0] * 0.1 p5 = figure(tools=TOOLS, title=y[:-9] + " - Assigned Centroid MS", width=1400, height=600, x_axis_label='m/z', y_axis_label='Abundance', y_range=[min(data["RA"]), max(data["RA"])], x_range=(msxlim[0] - stretch, msxlim[1] + stretch)) p5.segment(x0=0, x1=800, y0=0, y1=0, line_width=1, line_color="black") no1 = p5.segment(x0='mz', y0=0, x1='mz', y1='RA', source=nosource, line_width=linewidth, line_color="red", legend_label="Unassigned Peaks") #no2 =p5.scatter(x='mz', y='RA',source=nosource,fill_color='red',line_color=None,legend_label="Unassigned Peaks") #p5.scatter(x='mz', y='RA',source=source,fill_color='black',line_color=None,legend_label="Assigned Peaks") p5.segment(x0='mz', y0=0, x1='mz', y1='RA', source=source, line_width=linewidth, line_color="black", legend_label="Assigned Peaks") iso1 = p5.segment(x0='mz', y0=0, x1='mz', y1='RA', source=isosource, line_width=linewidth, line_color="green", legend_label="Isotologue Peaks") #iso2 =p5.scatter(x='mz', y='RA',source=isosource,fill_color='green',line_color=None, legend_label="Isotologue Peaks") hover = p5.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([('Formula', "@Formula"), ('Mass', "@mz{1.11111}"), ('Error (ppm)', "@Error{1.11}")]) taptool = p5.select(type=TapTool) taptool.callback = OpenURL(url=url) p5.yaxis[0].formatter = PrintfTickFormatter(format="%4.1e") #Bokeh 2 doesnt need JS buttons thanks to interactive legends #js_code1 = "iso1.glyph.visible = false; iso2.glyph.visible = false; no1.glyph.visible = false; no2.glyph.visible = false;" #cb1 = CustomJS(code=js_code1, args=dict(iso1=iso1,iso2=iso2,no1=no1,no2=no2)) #js_code2 = "iso1.glyph.visible = true; iso2.glyph.visible = true; no1.glyph.visible = true; no2.glyph.visible = true;" #cb2 = CustomJS(code=js_code2, args=dict(iso1=iso1,iso2=iso2,no1=no1,no2=no2)) #toggleOn = Button(label="Hide", button_type="success") #toggleOn.js_on_click(cb1) #toggleOff = Button(label="Show", button_type="success") #toggleOn.js_on_click(cb2) #top = layouts.Row(toggleOn,toggleOff) t3 = layouts.Column(p5) p5.legend.location = "top_left" p5.legend.click_policy = "hide" tab3 = Panel(child=t3, title="Centroid MS with Isotopomers and No Hits") downloadbutton = Button(label="Download", button_type="success") cb3 = CustomJS(args=dict(s2=s2), code=""" var data = s2.get('data'); var filetext = 'mz,Error,RA,Formula,HeteroClass\\n'; for (i=0; i < data['mz'].length; i++) { var currRow = [data['mz'][i].toString(), data['Error'][i].toString(), data['RA'][i].toString(), data['Formula'][i].toString(), data['HeteroClass'][i].toString().concat('\\n')]; var joined = currRow.join(); filetext = filetext.concat(joined); } var filename = 'data_result.csv'; var blob = new Blob([filetext], { type: 'text/csv;charset=utf-8;' }); //addresses IE if (navigator.msSaveBlob) { navigator.msSaveBlob(blob, filename); } else { var link = document.createElement("a"); link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = filename; link.target = "_blank"; link.style.visibility = 'hidden'; link.dispatchEvent(new MouseEvent('click')) } """) downloadbutton.js_on_event(ButtonClick, cb3) columns = [ TableColumn(field="mz", title="m/z", formatter=NumberFormatter(format="0.00000")), TableColumn(field="Error", title="Error (ppm)", formatter=NumberFormatter(format="0.00")), TableColumn(field="RA", title="Abundance"), TableColumn(field="Formula", title="Formula"), TableColumn(field="HeteroClass", title="Heteroatomic Class") ] data_table = DataTable(source=s2, columns=columns, width=1400, header_row=False, fit_columns=True) t4 = layouts.Column(data_table, downloadbutton) tab4 = Panel(child=t4, title="Selected Data Table") cb4 = CustomJS(args=dict(s2=s2, dt=data_table), code=""" var inds = cb_obj.get('selected')['1d'].indices; var d1 = cb_obj.get('data'); var d2 = s2.get('data'); if (inds.length == 0) { d2['mz'] = d1['mz'] d2['Error'] = d1['Error'] d2['RA'] = d1['RA'] d2['Formula'] = d1['Formula'] d2['HeteroClass'] = d1['HeteroClass'] } else if (inds.length != 0) { d2['mz'] = [] d2['Error'] = [] d2['RA'] = [] d2['Formula'] = [] d2['HeteroClass'] = [] for (i = 0; i < inds.length; i++) { d2['mz'].push(d1['mz'][inds[i]]) d2['Error'].push(d1['Error'][inds[i]]) d2['RA'].push(d1['RA'][inds[i]]) d2['Formula'].push(d1['Formula'][inds[i]]) d2['HeteroClass'].push(d1['HeteroClass'][inds[i]]) } } s2.trigger('change'); dt.trigger('change'); """) source.selected.js_on_change('indices', cb4) """ hetclasslist = hetclassintdf["HetClass"].tolist() hetclasslistnew = [] for x in hetclasslist: hetclasslistnew.append([x,x]) dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=hetclasslistnew) """ t1 = layouts.Row(p1, p4) t2 = layouts.Row(p2, p3) t12 = layouts.Column(t1, t2) tab1 = Panel(child=t12, title="Main") tabs = Tabs(tabs=[tab1, tab3, tab4]) for figs in [p1, p2, p3, p4, p5]: figs.xaxis.axis_label_text_font_size = "14pt" figs.xaxis.major_label_text_font_size = "14pt" figs.yaxis.axis_label_text_font_size = "14pt" figs.yaxis.major_label_text_font_size = "14pt" figs.title.text_font_size = "14pt" figs.toolbar_location = "above" with open(outputpath + 'templates/index.html', 'r') as f: template = Template(f.read()) #js_resources = JSResources(mode='inline') html = file_html(tabs, (CDN, CDN), "Interactive Van Krevelen Diagrams", template=template) output_file2 = outputpath + y[:-9] + '-plot.html' with open(output_file2, 'w') as f: f.write(html) view(output_file2)
def ShowGraph(graphDict): if not graphDict['ShowGraph']: logger.warning('%s is not shown.', graphDict['GraphTitle']) return if (len(graphDict['Yaxes']) <= 0) or (len(graphDict['items']) <= 0): debug('No axes or no lines defined for graph "%s"', graphDict['GraphTitle']) return if graphDict['DBHost'] not in DBHostDict.keys(): logger.warning('Unknown database host "%s" for plot "%s"' % (graphDict['DBHost'], graphDict['GraphTitle'])) return hostItem = DBHostDict[graphDict['DBHost']] # Signal that we want to reference local files for html output. res = Resources(mode='absolute') # output_file(graphDict["outputFile"], title=graphDict['GraphTitle']) plot = figure(title=graphDict['GraphTitle'], tools="pan,wheel_zoom,box_zoom,reset,save,box_select", x_axis_type='datetime', plot_width=1600, plot_height=800, active_drag="box_zoom", active_scroll="wheel_zoom") plot.title.align = "center" plot.title.text_font_size = "25px" plot.xaxis.axis_label = graphDict['XaxisTitle'] # plot.xaxis.ticker = DatetimeTicker(num_minor_ticks = 4) plot.xaxis.formatter = DatetimeTickFormatter(seconds=["%M:%S"], minutes=["%R"], minsec=["%M:%S"], hours=["%R"], hourmin=["%m/%d %R"], days=['%m/%d']) plot.toolbar.logo = None legend = Legend() # legend.items = [LegendItem(label="--- Left Axis ---" , renderers=[])] legend.items = [] ######### Setup Y axes ## Colors plot.yaxis.visible = False extra_y_ranges = {} for i in range(len(graphDict['Yaxes'])): ya = graphDict['Yaxes'][i] eyrName = 'Y%s_axis' % i clr = ya['color_map'] if clr is None: clr = graphDict["graph_color_map"] ya["cmap"] = myPalette.Palette(clr, graphDict['max_palette_len'], loggingLevel=helperFunctionLoggingLevel) clr = ya['color'] if clr is None: clr = "black" side = ya['location'] extra_y_ranges[eyrName] = DataRange1d(range_padding=0.01) plot.extra_y_ranges = extra_y_ranges plot.add_layout( LinearAxis(y_range_name=eyrName, axis_label=ya['title'], axis_line_color=clr, major_label_text_color=clr, axis_label_text_color=clr, major_tick_line_color=clr, minor_tick_line_color=clr), side) for i in range(len(graphDict['items'])): item = graphDict['items'][i] info('-------------- %s ------------' % item['dataname']) ya = graphDict['Yaxes'][item['axisNum']] colorGroup = ya['title'] query = item['query'].format( my_schema=hostItem['myschema'], ha_schema=hostItem['haschema'], BeginDate= '{BeginDate}' # Leave {BeginDate} unmolested; it is for later replacement. ) if item['dataTimeZone'] == 'UTC': dataTimeOffsetUTC = 0 else: dataTimeOffsetUTC = hostItem['ServerTimeFromUTC'] data = GetData(item['datafile'], query, dataTimeOffsetUTC, hostItem) if data is None: logger.warning( 'item "%s" of graph "%s" has no data and is skipped.' % (item['dataname'], graphDict['GraphTitle'])) continue else: debug('Got %s rows of data.' % data.size) data = ColumnDataSource(data) debug('data column names are: %s; num rows is: %s' % (data.column_names, data.to_df().size)) yRangeName = 'Y%s_axis' % item['axisNum'] for thisCol in data.column_names[1:]: debug('Column "%s" is plotted against y axis: "%s"' % (thisCol, yRangeName)) itemColor = item["color"] if item["color"] is None: itemColor = ya['cmap'].nextColor(colorGroup) else: debug('item color "%s" is defined in the item definition.' % itemColor) r = eval('''plot.%s(x=data.column_names[0] , y = thisCol , source=data , color = itemColor, alpha=0.5 , muted_color = itemColor, muted_alpha=1 , name = thisCol , y_range_name=yRangeName)''' % item['lineType']) for (k, v) in item['lineMods'].items(): s = 'r.%s = %s' % (k, v) debug('Executing line mod "%s"' % s) exec(s) extra_y_ranges[yRangeName].renderers.append(r) if item['includeInLegend']: legend.items.append(LegendItem(label=thisCol, renderers=[r])) plot.add_layout(legend) plot.legend.location = "top_left" plot.legend.click_policy = "mute" plot.add_tools( HoverTool( tooltips=[ ('', '$name') # use @{ } for field names with spaces , ('', '$y{0.0}') # use @{ } for field names with spaces , ('', '@Time{%F %T}') ], formatters={ '@Time': 'datetime' # use 'datetime' formatter for 'x' field # use default 'numeral' formatter for other fields })) # show(plot) html = file_html(plot, res, graphDict['GraphTitle']) f = open(graphDict["outputFile"], mode='w') f.write(html) f.close() view(graphDict["outputFile"], new='tab')
def create_bokeh_plot(df, s_source_dummy, s_source_full, s_sources, g_source_dummy, g_source_full, g_sources, selection_dates, selection_day_range): # assign unique variables for each DataSource required for each date within # the data timeline s_source1 = s_sources[0] s_source2 = s_sources[1] s_source3 = s_sources[2] s_source4 = s_sources[3] s_source5 = s_sources[4] s_source6 = s_sources[5] g_source1 = g_sources[0] g_source2 = g_sources[1] g_source3 = g_sources[2] g_source4 = g_sources[3] g_source5 = g_sources[4] g_source6 = g_sources[5] # create sentiment polarity-subjectivity scatter plot s_p = figure(plot_width=450, plot_height=450, x_axis_label='Polarity', y_axis_label='Subjectivity', tools=["crosshair", "pan", "box_zoom", "reset"]) # adjusting title text properties of the polarity-subjectivity scatter plot s_p.title.text = "Tweet Text Sentiment Analysis" s_p.title.align = "center" s_p.title.text_color = text_color s_p.title.text_font_size = title_font_size s_p.title.text_font = font s_p.title.text_font_style = font_style # adjusting axis properties of the polarity-subjectivity scatter plot s_p.axis.axis_label_text_font_style = font_style s_p.axis.axis_label_text_font_size = axis_label_font_size s_p.axis.axis_label_text_font = font s_p.axis.axis_label_text_color = text_color s_p.axis.major_label_text_font_size = major_label_font_size s_p.axis.major_label_text_font = font s_p.axis.major_label_text_color = text_color s_p.axis.axis_line_color = text_color s_p.xaxis.minor_tick_line_color = None s_p.yaxis.minor_tick_line_color = None # configure fixed axis numbers for consistent axis properties along # different scaled data s_p.y_range.start = -0.1 s_p.y_range.end = 1.1 s_p.x_range.start = -1.1 s_p.x_range.end = 1.1 # configure color palettes low-high for scatters resembling positive or # negative sentiments PiYG_reverse = tuple(reversed(PiYG[5])) mapper = LinearColorMapper(palette=PiYG_reverse, low=-1, high=1) # add scatter points to polarity-subjectivity scatter plot circle_glyph = s_p.circle(x='s_x', y='s_y', source=s_source_dummy, size=7, line_color='grey', fill_color=transform('s_x', mapper), fill_alpha=0.5, hover_color="pink") # add hover tool to polarity-subjectivity scatter plot s_p.add_tools( HoverTool(renderers=[circle_glyph], tooltips=[("Polarity", "@s_x"), ("Subjectivity", "@s_y"), ("User", "@user"), ("Date", "@created"), ("Location", "@location"), ("Tweet", "@tweet")])) # load shapefile of germany sf = gpd.read_file( os.path.join(resources_dir, 'shapefiles_ger', 'DEU_adm1.shp')) # Input GeoJSON source that contains features for plotting. This format # is required for plotting shapefiles in bokeh plots geosource = GeoJSONDataSource(geojson=sf.to_json()) # create empty map figure object g_p = figure(title='Tweet Locations', plot_height=450, plot_width=400, tools=["crosshair", "pan", "box_zoom", "reset"]) # adjusting title text properties of the geo plot g_p.title.text = "Tweet Locations" g_p.title.align = "center" g_p.title.text_color = text_color g_p.title.text_font_size = title_font_size g_p.title.text_font = font g_p.title.text_font_style = font_style # adjusting axis properties of the geo plot g_p.xgrid.grid_line_color = None g_p.ygrid.grid_line_color = None g_p.xaxis.minor_tick_line_color = None g_p.yaxis.minor_tick_line_color = None g_p.xaxis.major_tick_line_color = None g_p.yaxis.major_tick_line_color = None g_p.axis.axis_label_text_color = None g_p.axis.major_label_text_color = None g_p.axis.axis_line_color = None # create patches of the german states using the geosources g_p.patches('xs', 'ys', source=geosource, fill_color='#ffbaba', line_color='#f5f5f5', line_width=1, fill_alpha=1) # geo source scatter plot of city counts scatter = g_p.scatter('g_x', 'g_y', source=g_source_dummy, line_color='white', fill_color='teal', fill_alpha=0.5, radius='bins') # create hover tool g_p.add_tools( HoverTool(renderers=[scatter], tooltips=[("City", "@name"), ("Tweets", "@count"), ("Coordinates", "@g_x, @g_y")])) # requires to add extra quotes to the selection dates for the if queries # inside the js callback syntax selection_dates_js = ["'" + option + "'" for option in selection_dates] # add custom JS callback for changing data based on date range callback = CustomJS(args={ 'source1': s_source_dummy, 'source2': s_source1, 'source3': s_source2, 'source4': s_source3, 'source5': s_source4, 'source6': s_source5, 'source7': s_source6, 'source8': s_source_full, 'source9': g_source_dummy, 'source10': g_source1, 'source11': g_source2, 'source12': g_source3, 'source13': g_source4, 'source14': g_source5, 'source15': g_source6, 'source16': g_source_full }, code=""" var data1 = source1.data; var data2 = source2.data; var data3 = source3.data; var data4 = source4.data; var data5 = source5.data; var data6 = source6.data; var data7 = source7.data; var data8 = source8.data; var data9 = source9.data; var data10 = source10.data; var data11 = source11.data; var data12 = source12.data; var data13 = source13.data; var data14 = source14.data; var data15 = source15.data; var data16 = source16.data; var f = cb_obj.value; if (f == %s) { for (var e in data1) delete data1[e]; for (var g in data9) delete data9[g]; data1['s_x'] = data2['s_x']; data1['s_y'] = data2['s_y']; data1['user'] = data2['user']; data1['created'] = data2['created']; data1['location'] = data2['location']; data1['tweet'] = data2['tweet']; data9['g_x'] = data10['g_x']; data9['g_y'] = data10['g_y']; data9['name'] = data10['name']; data9['count'] = data10['count']; data9['bins'] = data10['bins']; } if (f == %s) { for (var e in data1) delete data1[e]; for (var g in data9) delete data9[g]; data1['s_x'] = data3['s_x']; data1['s_y'] = data3['s_y']; data1['user'] = data3['user']; data1['created'] = data3['created']; data1['location'] = data3['location']; data1['tweet'] = data3['tweet']; data9['g_x'] = data11['g_x']; data9['g_y'] = data11['g_y']; data9['name'] = data11['name']; data9['count'] = data11['count']; data9['bins'] = data11['bins']; } if (f == %s) { for (var e in data1) delete data1[e]; for (var g in data9) delete data9[g]; data1['s_x'] = data4['s_x']; data1['s_y'] = data4['s_y']; data1['user'] = data4['user']; data1['created'] = data4['created']; data1['location'] = data4['location']; data1['tweet'] = data4['tweet']; data9['g_x'] = data12['g_x']; data9['g_y'] = data12['g_y']; data9['name'] = data12['name']; data9['count'] = data12['count']; data9['bins'] = data12['bins']; } if (f == %s) { for (var e in data1) delete data1[e]; for (var g in data9) delete data9[g]; data1['s_x'] = data5['s_x']; data1['s_y'] = data5['s_y']; data1['user'] = data5['user']; data1['created'] = data5['created']; data1['location'] = data5['location']; data1['tweet'] = data5['tweet']; data9['g_x'] = data13['g_x']; data9['g_y'] = data13['g_y']; data9['name'] = data13['name']; data9['count'] = data13['count']; data9['bins'] = data13['bins']; } if (f == %s) { for (var e in data1) delete data1[e]; for (var g in data9) delete data9[g]; data1['s_x'] = data6['s_x']; data1['s_y'] = data6['s_y']; data1['user'] = data6['user']; data1['created'] = data6['created']; data1['location'] = data6['location']; data1['tweet'] = data6['tweet']; data9['g_x'] = data14['g_x']; data9['g_y'] = data14['g_y']; data9['name'] = data14['name']; data9['count'] = data14['count']; data9['bins'] = data14['bins']; } if (f == %s) { for (var e in data1) delete data1[e]; for (var g in data9) delete data9[g]; data1['s_x'] = data7['s_x']; data1['s_y'] = data7['s_y']; data1['user'] = data7['user']; data1['created'] = data7['created']; data1['location'] = data7['location']; data1['tweet'] = data7['tweet']; data9['g_x'] = data15['g_x']; data9['g_y'] = data15['g_y']; data9['name'] = data15['name']; data9['count'] = data15['count']; data9['bins'] = data15['bins']; } if (f == %s) { for (var e in data1) delete data1[e]; for (var g in data9) delete data9[g]; data1['s_x'] = data8['s_x']; data1['s_y'] = data8['s_y']; data1['user'] = data8['user']; data1['created'] = data8['created']; data1['location'] = data8['location']; data1['tweet'] = data8['tweet']; data9['g_x'] = data16['g_x']; data9['g_y'] = data16['g_y']; data9['name'] = data16['name']; data9['count'] = data16['count']; data9['bins'] = data16['bins']; } source1.change.emit(); source9.change.emit(); """ % (selection_dates_js[0], selection_dates_js[1], selection_dates_js[2], selection_dates_js[3], selection_dates_js[4], selection_dates_js[5], selection_dates_js[6])) select = Select(title='Choose date from timeline:', value=selection_dates[0], options=selection_dates, sizing_mode="stretch_width") select.js_on_change('value', callback) color_bar = ColorBar(color_mapper=mapper, label_standoff=10, width=12, major_label_text_font_size='14px', major_label_text_font=font, location=(0, 0)) s_p.add_layout(color_bar, 'right') # fixed widgets column contains select dropdown menu dropdown = column(select, sizing_mode="fixed", height=50, width=800) # placeholder div containers ph_fig_sep = Div(text="", height=50, width=20) ph_widget_sep = Div(text="", height=20, width=500) # create whisker sentiment plots for polarity and subjectivity # import whisker_plot to avoid import exceptions due to circular # dependencies from whisker_plot import whisker_sentiment, whisker_city_count w_pol = whisker_sentiment(df, 'polarity') w_sub = whisker_sentiment(df, 'subjectivity') w_count = whisker_city_count(df, selection_day_range) # assembling layout together layout = column(row(ph_fig_sep, ph_fig_sep, dropdown), row(ph_widget_sep), row(s_p, ph_fig_sep, g_p), row(ph_widget_sep), row(w_pol, ph_fig_sep, w_sub), row(ph_widget_sep), row(w_count), row(ph_widget_sep), sizing_mode="stretch_both") # if required plot can be exported as png #export_png(layout, filename="plot.png") # calling create_html_template function to assemble bokeh plots into # custom styled html/css templates html = create_html_template(layout) filename = 'index.html' # generate output file as html with open((os.path.join(docs_dir, filename)), "w", encoding="utf-8") as f: f.write(html) view(filename)
def show(self): filename = self._generate_output(self._fp) view(filename) self._reset() self._num_plots += 1
def test_view_bad_new(): with pytest.raises(RuntimeError) as e: bub.view("foo", new="junk") assert str(e) == "invalid 'new' value passed to view: 'junk', valid values are: 'same', 'window', or 'tab'"
# data, ptid_md = filterData(data, ptid_md, method='pass') isError, err_html = _errorDisplay(data, ptid_md, measures_md) if isError is False: data, ptid_md, measures_md, rowDend, colDend = clusterData( data, ptid_md, measures_md, metric='euclidean', method='ward', standardize=False, impute=True) # Creating overall data source sources = initSources(data, ptid_md, measures_md, raw_data, transform="b'none'", params=["0", "2, 2", "1, 1"]) cbDict = initCallbacks(sources) p = generateLayout(sources, cbDict, rowDend, colDend) else: with io.open('MetaVisError.html', mode='w', encoding='utf-8') as g: g.write(err_html) view('MetaVisError.html') print(isError)
<!-- Custom Added Code To Provide External Resources --> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <!-- ############################################### --> {% endblock %} {% endblock %} </head> {% endblock %} {% block body %} <body> {% block inner_body %} {% block contents %} {% for doc in docs %} {{ embed(doc) if doc.elementid }} {% for root in doc.roots %} {% block root scoped %} {{ embed(root) | indent(10) }} {% endblock %} {% endfor %} {% endfor %} {% endblock %} {{ plot_script | indent(8) }} {% endblock %} </body> {% endblock %} </html> """ layout = column(p, tbutton) save(layout, template=external_src_template) view(output_filename + '.html')
def stop(PORT=FAKE_LISTENER_PORT): view(f"http://localhost:{PORT}/shutdown")
if "docs" not in globals(): docs = [] page = column() sourceBuySell: ColumnDataSource = ColumnDataSource({ # ['buyPressure', 'index', 'sellPressure', 'time'] 'buyPressure':[], 'sellPressure':[], 'index': [], }) sourceVolume:ColumnDataSource = ColumnDataSource({ # ['index', 'nnBuy', 'nnSell', 'time', 'totalValue'] 'index': [], 'nnBuy': [], 'nnSell': [], 'totalValue': [],}) def attachDocToServer(doc: Document): global page, sourceVolume, sourceBuySell page, activate, sourceBuySell, sourceVolume = makeMasterPlot() doc.add_root(column(page)) docs.append(doc) activate() if __name__ == "__main__": s = Server({'/': Application(FunctionHandler(attachDocToServer))}, num_proc=16, port=BOKEH_PORT, allow_websocket_origin=["*"]) s.start() threading_func_wrapper(s.io_loop.start, delay=0.01) threading_func_wrapper(lambda: view(f"http://localhost:{BOKEH_PORT}"), 0.5)
def test_view_args(): db = bub.DummyWebBrowser bub.DummyWebBrowser = _RecordingWebBrowser # test http locations used as-is bub.view("http://foo", browser="none") assert _open_args == (('http://foo',), {'autoraise': True, 'new': 0}) # test non-http locations treated as local files bub.view("/foo/bar", browser="none") if sys.platform == "win32": assert _open_args == (('file://' + os.path.splitdrive(os.getcwd())[0] + '\\foo\\bar',), {'autoraise': True, 'new': 0}) else: assert _open_args == (('file:///foo/bar',), {'autoraise': True, 'new': 0}) # test autoraise passed to open bub.view("http://foo", browser="none", autoraise=False) assert _open_args == (('http://foo',), {'autoraise': False, 'new': 0}) # test handling of new values bub.view("http://foo", browser="none", new="same") assert _open_args == (('http://foo',), {'autoraise': True, 'new': 0}) bub.view("http://foo", browser="none", new="window") assert _open_args == (('http://foo',), {'autoraise': True, 'new': 1}) bub.view("http://foo", browser="none", new="tab") assert _open_args == (('http://foo',), {'autoraise': True, 'new': 2}) bub.DummyWebBrowser = db
def after_write_file(self, args, filename, doc): if args.show: from bokeh.util.browser import view view(filename)
def test_view_args(): db = bub.DummyWebBrowser bub.DummyWebBrowser = _RecordingWebBrowser # test http locations used as-is bub.view("http://foo", browser="none") assert _open_args == (('http://foo', ), {'autoraise': True, 'new': 0}) # test non-http locations treated as local files bub.view("/foo/bar", browser="none") assert _open_args == (('file:///foo/bar', ), {'autoraise': True, 'new': 0}) # test autoraise passed to open bub.view("http://foo", browser="none", autoraise=False) assert _open_args == (('http://foo', ), {'autoraise': False, 'new': 0}) # test handling of new values bub.view("http://foo", browser="none", new="same") assert _open_args == (('http://foo', ), {'autoraise': True, 'new': 0}) bub.view("http://foo", browser="none", new="window") assert _open_args == (('http://foo', ), {'autoraise': True, 'new': 1}) bub.view("http://foo", browser="none", new="tab") assert _open_args == (('http://foo', ), {'autoraise': True, 'new': 2}) bub.DummyWebBrowser = db
def test_view_args() -> None: db = bub.DummyWebBrowser bub.DummyWebBrowser = _RecordingWebBrowser # test http locations used as-is bub.view("http://foo", browser="none") assert _open_args == (('http://foo', ), {'autoraise': True, 'new': 0}) # test non-http locations treated as local files bub.view("/foo/bar", browser="none") if sys.platform == "win32": assert _open_args == (('file://' + os.path.splitdrive(os.getcwd())[0] + '\\foo\\bar', ), { 'autoraise': True, 'new': 0 }) else: assert _open_args == (('file:///foo/bar', ), { 'autoraise': True, 'new': 0 }) # test autoraise passed to open bub.view("http://foo", browser="none", autoraise=False) assert _open_args == (('http://foo', ), {'autoraise': False, 'new': 0}) # test handling of new values bub.view("http://foo", browser="none", new="same") assert _open_args == (('http://foo', ), {'autoraise': True, 'new': 0}) bub.view("http://foo", browser="none", new="window") assert _open_args == (('http://foo', ), {'autoraise': True, 'new': 1}) bub.view("http://foo", browser="none", new="tab") assert _open_args == (('http://foo', ), {'autoraise': True, 'new': 2}) bub.DummyWebBrowser = db
def write_to_html(plots, type=0, filename='output.html', title='Title'): ''' Outputs the files into an html file :param filename: :param labels: :param plots: :return: ''' # Define our html template for out plots template = Template(''' <!DOCTYPE html> <html lang="en"> <head> <title>{{ title }}</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> {{ js_resources }} {{ css_resources }} </head> <body> <div class="container-fluid"> <!-- <div class="jumbotron"> <h1>Title</h1> <p>Description</p> </div> --!> <h1>{{ title }}</h1> <div class="row"> <div class="col-8"> <h3>Manhattan plots</h3> <p>Group 1</p> {{ plot_div.p0 }} <p>Group 2</p> {{ plot_div.p1 }} <p class="text-muted"><a href="https://github.com/khramts/assocplots">Generated with ASSOCPLOTS package</a></p> </div> <div class="col-4"> <h3>Quantile-Quantile Plot</h3> {{ plot_div.p2 }} <p>Selected elements</p> {{ plot_div.p3 }} </div> </div> </div> <!-- <footer class="footer"> <div class="container-fluid"> <p class="text-muted"><a href="https://github.com/khramts/assocplots">Generated with ASSOCPLOTS package</a></p> </div> </footer> --!> {{ plot_script }} </body> </html> ''') resources = INLINE js_resources = resources.render_js() css_resources = resources.render_css() script, div = components({'p0': plots[0],'p1': plots[1],'p2': plots[2],'p3': plots[3]}) html = template.render(js_resources=js_resources, css_resources=css_resources, plot_script=script, plot_div=div, title = title) with open(filename, 'w') as f: f.write(html) view(filename)
<p> This Bokeh Div adds the style classes:<p> <pre> .bk.custom { border-radius: 0.5em; padding: 1em; } .bk.custom-1 { border: 3px solid #2397D8; } </pre> """) div1.css_classes = ["custom", "custom-1"] div2 = Div(text=""" <p> This Bokeh Div adds the style classes:<p> <pre> .bk.custom { border-radius: 0.5em; padding: 1em; } .bk.custom-2 { border: 3px solid #14999A; background-color: whitesmoke; } </pre> """) div2.css_classes = ["custom", "custom-2"] save(column(p, div1, div2), template=template) view("css_classes.html")
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 # Stick the plot and the slider together layout = column(plot, slider) # Open our custom template with open('gapminder_template.jinja', 'r') as f: template = Template(f.read()) # Use inline resources, render the html and open js_resources = JSResources(mode='inline') title = "Bokeh - Gapminder Bubble Plot" html = file_html(layout, resources=(js_resources, None), title=title, template=template) output_file = 'gapminder.html' with io.open(output_file, mode='w', encoding='utf-8') as f: f.write(html) view(output_file)
def write_to_html(plots, type=0, filename='output.html', title='Title'): ''' Outputs the files into an html file :param filename: :param labels: :param plots: :return: ''' # Define our html template for out plots template = Template(''' <!DOCTYPE html> <html lang="en"> <head> <title>{{ title }}</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> {{ js_resources }} {{ css_resources }} </head> <body> <div class="container-fluid"> <!-- <div class="jumbotron"> <h1>Title</h1> <p>Description</p> </div> --!> <h1>{{ title }}</h1> <div class="row"> <div class="col-sm-8"> <h3>Manhattan plots</h3> <p>Group 1</p> {{ plot_div.p0 }} <p>Group 2</p> {{ plot_div.p1 }} <p class="text-muted"><a href="https://github.com/khramts/assocplots">Generated with ASSOCPLOTS package</a></p> </div> <div class="col-sm-4"> <h3>Quantile-Quantile Plot</h3> {{ plot_div.p2 }} <p>Selected elements</p> {{ plot_div.p3 }} </div> </div> </div> <!-- <footer class="footer"> <div class="container-fluid"> <p class="text-muted"><a href="https://github.com/khramts/assocplots">Generated with ASSOCPLOTS package</a></p> </div> </footer> --!> {{ plot_script }} </body> </html> ''') resources = INLINE js_resources = resources.render_js() css_resources = resources.render_css() script, div = components({'p0': plots[0],'p1': plots[1],'p2': plots[2],'p3': plots[3]}) html = template.render(js_resources=js_resources, css_resources=css_resources, plot_script=script, plot_div=div, title = title) with open(filename, 'w') as f: f.write(html) view(filename)
LegendItem(label="CR2", renderers=[cr2, ln2]), LegendItem(label="CR3", renderers=[cr3]), ] legend = lambda **kwargs: Legend( background_fill_alpha=0.7, items=legends(), click_policy="hide", **kwargs) plot.add_layout(legend(location="center_left", orientation="vertical")) plot.add_layout(legend(location="center", orientation="vertical")) plot.add_layout(legend(location="top_center", orientation="horizontal")) plot.add_layout(legend(location="top_right", orientation="horizontal")) plot.add_layout(legend(location="bottom_right", orientation="horizontal")) plot.add_layout(legend(location=(0, 0), orientation="vertical", name="(0, 0)")) plot.add_layout( legend(location="center", orientation="horizontal", name="above"), 'above') plot.add_layout( legend(location="center", orientation="horizontal", name="below"), 'below') plot.add_layout(legend(location="center", orientation="vertical", name="left"), 'left') plot.add_layout( legend(location="center", orientation="vertical", name="right"), 'right') doc = Document() doc.add_root(plot) if __name__ == "__main__": filename = "synthetic.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "A synthetic example")) print("Wrote %s" % filename) view(filename)
<pre> .p { width: 33.3%; padding: 50px; } .p:nth-child(1) { background-color: red; } .p:nth-child(2) { background-color: green; } .p:nth-child(3) { background-color: blue; } </pre> </p> </div> <div class="plots"> <div class="p">{{ embed(roots.p0) }}</div> <div class="p">{{ embed(roots.p1) }}</div> <div class="p">{{ embed(roots.p2) }}</div> </div> </div> {% endblock %} """ x = [1, 2, 3] y = [1, 2, 3] p0 = figure(name="p0", sizing_mode="scale_width") p0.scatter(x, y, size=20, fill_color="red") p1 = figure(name="p1", sizing_mode="scale_width") p1.scatter(x, y, size=20, fill_color="green") p2 = figure(name="p2", sizing_mode="scale_width") p2.scatter(x, y, size=20, fill_color="blue") save([p0, p1, p2], template=template) view("custom_layout.html")