Python bokeh.embed.components() Examples

The following are 28 code examples of bokeh.embed.components(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bokeh.embed , or try the search function .
Example #1
Source File: app.py    From blog-code-examples with MIT License 6 votes vote down vote up
def chart(bars_count):
    if bars_count <= 0:
        bars_count = 1

    data = {"days": [], "bugs": [], "costs": []}
    for i in range(1, bars_count + 1):
        data['days'].append(i)
        data['bugs'].append(random.randint(1,100))
        data['costs'].append(random.uniform(1.00, 1000.00))

    hover = create_hover_tool()
    plot = create_bar_chart(data, "Bugs found per day", "days",
                            "bugs", hover)
    script, div = components(plot)

    return render_template("chart.html", bars_count=bars_count,
                           the_div=div, the_script=script) 
Example #2
Source File: stocks_w_bokeh_example.py    From spyre with MIT License 6 votes vote down vote up
def getHTML(self, params):
        ticker = params['ticker']
        if ticker == 'empty':
            ticker = params['custom_ticker'].upper()
        df = self.getData(params)  # get data
        try:
            bokeh_plot = plotting.line(
                df.index, df['Close'], color='#1c2980',
                legend="Close", x_axis_type="datetime", title=ticker
            )
        except AttributeError:
            bokeh_plot = plotting.figure(x_axis_type='datetime', title=ticker)
            bokeh_plot.line(df.index, df['Close'], color='#1c2980', legend="Close")
        bokeh_plot.line(df.index, df['High'], color='#80641c', legend="High")
        bokeh_plot.line(df.index, df['Low'], color='#80321c', legend="Low")

        script, div = components(bokeh_plot, CDN)
        html = "%s\n%s" % (script, div)
        return html 
Example #3
Source File: base.py    From Pandas-Bokeh with MIT License 6 votes vote down vote up
def embedded_html(fig, resources="CDN"):
    """Returns an html string that contains all neccessary CSS&JS files, 
    together with the div containing the Bokeh plot. As input, a figure fig
    is expected."""

    html_embedded = ""
    if resources == "CDN":
        js_css_resources = get_bokeh_resources()
        html_embedded += js_css_resources
    elif resources == "raw":
        raise NotImplementedError("<resources> = raw has to be implemented by Thomas!")
    elif resources == None:
        pass
    else:
        raise ValueError("<resources> only accept 'CDN', 'raw' or None.")

    # Add plot script and div
    script, div = components(fig)
    html_embedded += "\n\n" + div + "\n\n" + script

    return html_embedded 
Example #4
Source File: pimp_comparison_table.py    From CAVE with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_html(self, d=None, tooltip=None):
        self.run()
        if len(self.result) == 1 and None in self.result:
            self.logger.debug("Detected None-key, abstracting away...")
            self.result = self.result[None]
        if d is not None:
            d[self.name] = OrderedDict()
        script, div = "", ""
        for b, t in self.result.items():
            s_, d_ = components(t) if b == 'bokeh' else components(t['bokeh'])
            script += s_
            div += d_
            if d is not None:
                if b == 'bokeh':
                    d[self.name] = {
                     "bokeh": (s_, d_),
                     "tooltip": self.__doc__,
                    }
                else:
                    d[self.name][b] = {
                        "bokeh": (s_, d_),
                        "tooltip": self.__doc__,
                    }
        return script, div 
Example #5
Source File: configurator_footprint.py    From CAVE with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_html(self, d=None, tooltip=None):
        bokeh_components = components(self.plot())
        if d is not None:
            if self.num_quantiles == 1 or self.use_timeslider:  # No need for "Static" with one plot / time slider activated
                d[self.name] = {
                    "bokeh" : bokeh_components,
                    "tooltip": self.__doc__,
                }
            else:
                d[self.name] = {
                    "tooltip": self.__doc__,
                    "Interactive" : {"bokeh": (bokeh_components)},
                }
                if all([True for p in self.cfp_paths if os.path.exists(p)]):  # If the plots were actually generated
                    d[self.name]["Static"] = {"figure": self.cfp_paths}
                else:
                    d[self.name]["Static"] = {
                            "else": "This plot is missing. Maybe it was not generated? "
                                    "Check if you installed selenium and phantomjs "
                                    "correctly to activate bokeh-exports. "
                                    "(https://automl.github.io/CAVE/stable/faq.html)"}
        return bokeh_components 
Example #6
Source File: parallel_coordinates.py    From CAVE with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_bokeh(self, return_components=False):
        """ If components is specified, will return script, div-tuple """
        if not self.data:
            self._preprocess()
        result = self.result if return_components else {}
        for budget, dataframe in self.data.items():
            plot = self._plot_budget(dataframe)
            if return_components:
                result[budget] = {'bokeh': components(plot)}
            else:
                result[budget] = plot

        # If only one budget, we don't need an extra tab...
        if len(result) == 1:
            result = list(result.values())[0]

        return result 
Example #7
Source File: app.py    From pairstrade-fyp-2019 with MIT License 6 votes vote down vote up
def index():
	# Create the plot
	plot = create_figure()
	# tag here means the tag to reference to the new bokeh chart, saved as a js file
	js, plot_tag = components(plot, CDN, "/Users/brendantham/Desktop/FYP/Flask/static/plots")

	# TODO: 
	# 1) fix URLS
	# 2) figure out where to store the js files for future load use 

	# with open('/Users/brendantham/Desktop/FYP/Flask/static/plots/plot1.js', 'w') as f:  
	# 	f.write(js)
		
	return render_template("index.html", script1 = js, plot1 = plot_tag)

# With debug=True, Flask server will auto-reload 
# when there are code changes 
Example #8
Source File: domain.py    From memex-explorer with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def create(self):
        self.source = self.update_source()

        max_data = max(max(self.source.data['relevant']), max(self.source.data['crawled']))
        xdr = Range1d(start=0, end=max_data)

        p = figure(plot_width=400, plot_height=400,
                   title="Domains Sorted by %s" % self.sort, x_range = xdr,
                   y_range = FactorRange(factors=self.source.data['domain']),
                   tools='reset, resize, save')

        p.rect(y='domain', x='crawled_half', width="crawled", height=0.75,
               color=DARK_GRAY, source =self.source, legend="crawled")
        p.rect(y='domain', x='relevant_half', width="relevant", height=0.75,
               color=GREEN, source =self.source, legend="relevant")

        p.ygrid.grid_line_color = None
        p.xgrid.grid_line_color = '#8592A0'
        p.axis.major_label_text_font_size = "8pt"

        script, div = components(p)

        if os.path.exists(self.crawled_data) and os.path.exists(self.relevant_data):
            return (script, div) 
Example #9
Source File: app.py    From blog-code-examples with MIT License 6 votes vote down vote up
def chart(num_bars):
    """Creates a bar chart with the desired number of bars in a chart."""
    if num_bars <= 0:
        num_bars = 1
    data = {"days": [], "bugs": [], "costs": []}
    for i in range(1, num_bars + 1):
        data['days'].append(i)
        data['bugs'].append(random.randint(1,100))
        data['costs'].append(random.uniform(1.00, 1000.00))

    hover = create_hover_tool()
    plot = create_bar_chart(data, "Bugs found per day", "days",
                            "bugs", hover)
    script, div = components(plot)
    return template(TEMPLATE_STRING, bars_count=num_bars,
                      the_div=div, the_script=script) 
Example #10
Source File: test_all.py    From ipyvolume with MIT License 6 votes vote down vote up
def test_bokeh():
    from bokeh.plotting import figure
    import ipyvolume.bokeh

    x, y, z = np.random.random((3, 100))

    p3.figure()
    scatter = p3.scatter(x, y, z)

    tools = "wheel_zoom,box_zoom,box_select,lasso_select,help,reset,"
    p = figure(title="E Lz space", tools=tools, width=500, height=500)
    r = p.circle(x, y, color="navy", alpha=0.2)
    ipyvolume.bokeh.link_data_source_selection_to_widget(r.data_source, scatter, 'selected')

    from bokeh.resources import CDN
    from bokeh.embed import components

    script, div = components(p)
    template_options = dict(
        extra_script_head=script + CDN.render_js() + CDN.render_css(),
        body_pre="<h2>Do selections in 2d (bokeh)<h2>" + div + "<h2>And see the selection in ipyvolume<h2>",
    )
    ipyvolume.embed.embed_html(
        "tmp/bokeh.html", [p3.gcc(), ipyvolume.bokeh.wmh], all_states=True, template_options=template_options
    ) 
Example #11
Source File: calculation.py    From qmpy with MIT License 6 votes vote down vote up
def calculation_view(request, calculation_id):
    calculation = Calculation.objects.get(pk=calculation_id)
    data = get_globals()
    data['calculation'] = calculation
    data['stdout'] = ''
    data['stderr'] = ''

    if os.path.exists(os.path.join(calculation.path, 'stdout.txt')):
        with open(os.path.join(calculation.path, 'stdout.txt')) as fr:
            data['stdout'] = fr.read()
    if os.path.exists(os.path.join(calculation.path, 'stderr.txt')):
        with open(os.path.join(calculation.path, 'stderr.txt')) as fr:
            data['stderr'] = fr.read()
    try:
        data['incar'] = ''.join(calculation.read_incar())
    except VaspError:
        data['incar'] = 'Could not read INCAR'

    if not calculation.dos is None:
        script, div = components(calculation.dos.bokeh_plot)
        data['dos'] = script
        data['dosdiv'] = div

    return render_to_response('analysis/calculation.html',
            data, RequestContext(request)) 
Example #12
Source File: my_bokeh_app.py    From scipy2015-blaze-bokeh with MIT License 6 votes vote down vote up
def index():
    # Create layout
    c_map = climate_map()
    ts = timeseries()
    l = legend()
    t = title()

    map_legend = hplot(c_map, l)
    layout = vplot(t, map_legend, ts)

    plot_resources = RESOURCES.render(
        js_raw=INLINE.js_raw,
        css_raw=INLINE.css_raw,
        js_files=INLINE.js_files,
        css_files=INLINE.css_files,
    )
    script, div = components(layout, INLINE)
    html = flask.render_template(
        'embed.html',
        plot_script=script,
        plot_div=div,
        plot_resources=plot_resources,
    )
    return encode_utf8(html) 
Example #13
Source File: cost_over_time.py    From CAVE with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_html(self, d=None, tooltip=None):
        script, div = components(self.plot())
        if d is not None:
            d[self.name] = {
                "bokeh" : (script, div),
                "tooltip" : self.__doc__,
            }
        return script, div 
Example #14
Source File: bokeh_view.py    From tethys with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, plot_input, height='520px', width='100%',
                 attributes='', classes='', divid='', hidden=False):
        """
        Constructor
        """
        # Initialize the super class
        super().__init__(attributes, classes)
        self.script, self.div = components(plot_input)
        self.height = height
        self.width = width
        self.divid = divid
        self.hidden = hidden 
Example #15
Source File: main-bokeh.py    From python-examples with MIT License 5 votes vote down vote up
def embed():
    """Get compopents and use in own HTML"""
    # https://bokeh.pydata.org/en/latest/docs/user_guide/embed.html
    # If you have installed bokeh 1.0.1 (bokeh.__version__) 
    # then you have to use `bokeh-1.0.1.min.js`, `bokeh-1.0.1.min.css`
    # It will not work if there are different versions
    
    #import bokeh
    #print(bokeh.__version__)
    
    keys = [1,2,3,4]
    values = [1,4,2,3]

    plot = figure(
        title='Bar Chart showing Side Effects of Breast \
#Cancer Medication(s) With Their Corrresponding Percentages Of \
#Occurence', 
        x_axis_label='Side Effects', 
        y_axis_label='Percentages of Occurence of Side Effects'
    )

    plot.line(keys, values) # legend=??
 
    script, div = components(plot)

    return '''<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.pydata.org/bokeh/release/bokeh-1.0.1.min.css" type="text/css" />
<script type="text/javascript" src="http://cdn.pydata.org/bokeh/release/bokeh-1.0.1.min.js"></script>
</head>
<body>''' + div + script + '''
</body>
</html>''' 
Example #16
Source File: unemployment_example.py    From spyre with MIT License 5 votes vote down vote up
def getHTML(self, params):
        state = params['state']
        if state == 'all':
            data = self.data
        else:
            data = self.data[self.data['state'] == state]

        TOOLS = "pan,wheel_zoom,box_zoom,reset,hover,previewsave"

        try:
            fig = plotting.patches(
                data['lons'], data['lats'], fill_color=data['color'], fill_alpha=0.7, tools=TOOLS,
                line_color="white", line_width=0.5, title=state.upper() + " Unemployment 2009"
            )
        except Exception:
            fig = plotting.figure(title=state.upper() + " Unemployment 2009", tools=TOOLS)
            fig.patches(
                data['lons'], data['lats'], fill_color=data['color'],
                fill_alpha=0.7, line_color="white", line_width=0.5
            )

        hover = fig.select(dict(type=HoverTool))
        hover.tooltips = OrderedDict([
            ("index", "$index")
        ])

        script, div = components(fig, CDN)
        html = "%s\n%s" % (script, div)
        return html 
Example #17
Source File: loss_curves.py    From CAVE with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_html(self, d=None, tooltip=None):
        script, div = components(self.plot())
        if d is not None:
            d[self.name] = {
                "bokeh" : (script, div),
                "tooltip" : self.__doc__,
            }
        return script, div 
Example #18
Source File: base_parameter_importance.py    From CAVE with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_html(self, d=None, tooltip=None):
        if self.runscontainer.analyzing_options['Parameter Importance'].getboolean('whisker_quantiles_plot'):
            self.result['Whisker Plot'] = {'bokeh': components(self.plot_whiskers()),
                                           'tooltip': "Each dot is a parallel run (or folder) of the input data "
                                                      "and the whiskers are quartiles."}

        return super().get_html(d, tooltip) 
Example #19
Source File: views.py    From memex-explorer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def pvalue_plot( date, pvalues_lower, pvalues_upper ):
    plot = figure(x_axis_type = "datetime", plot_height=250, plot_width=600)
    plot.line(date, pvalues_lower, legend='Lower', line_color='green')
    plot.line(date, pvalues_upper, legend='Upper', line_color='red')
    plot.legend.orientation = "top_left"
    plot.title = '-log(P Values)'

    script, div = components(plot, CDN)
    return { 'script': script, 'div': div } 
Example #20
Source File: budget_correlation.py    From CAVE with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_html(self, d=None, tooltip=None):
        script, div = components(self.plot())
        if d is not None:
            d["Budget Correlation"] = {
                "bokeh": (script, div),
                "tooltip": self.__doc__,
            }
        return script, div 
Example #21
Source File: bohb_learning_curves.py    From CAVE with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_html(self, d=None, tooltip=None):
        script, div = components(self.plot())
        if d is not None:
            d["BOHB Learning Curves"] = {"bokeh": (script, div), "tooltip": self.__doc__}
        return script, div 
Example #22
Source File: dataIndicatorsHandler.py    From stock with Apache License 2.0 5 votes vote down vote up
def add_plot(stockStat, conf):
    p_list = []
    logging.info("############################", type(conf["dic"]))
    # 循环 多个line 信息。
    for key, val in enumerate(conf["dic"]):
        logging.info(key)
        logging.info(val)

        p1 = figure(width=1000, height=150, x_axis_type="datetime")
        # add renderers
        stockStat["date"] = pd.to_datetime(stockStat.index.values)
        # ["volume","volume_delta"]
        # 设置20个颜色循环,显示0 2 4 6 号序列。
        p1.line(stockStat["date"], stockStat[val], color=Category20[20][key * 2])

        # Set date format for x axis 格式化。
        p1.xaxis.formatter = DatetimeTickFormatter(
            hours=["%Y-%m-%d"], days=["%Y-%m-%d"],
            months=["%Y-%m-%d"], years=["%Y-%m-%d"])
        # p1.xaxis.major_label_orientation = radians(30) #可以旋转一个角度。

        p_list.append([p1])

    gp = gridplot(p_list)
    script, div = components(gp)
    return {
        "script": script,
        "div": div,
        "title": conf["title"],
        "desc": conf["desc"]
    } 
Example #23
Source File: harvest.py    From memex-explorer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def create(self):
        self.source = self.update_source()

        p = figure(plot_width=400, plot_height=400,
                   title="Harvest Plot", x_axis_type='datetime',
                   tools='pan, wheel_zoom, box_zoom, reset, resize, save, hover')

        p.line(x="timestamp", y="relevant_pages", color=GREEN, line_width=0.2,
               legend="relevant", source=self.source)
        p.scatter(x="timestamp", y="relevant_pages", fill_alpha=0.6,
                  color=GREEN, source=self.source)

        p.line(x="timestamp", y="downloaded_pages", color=DARK_GRAY, line_width=0.2,
               legend="downloaded", source=self.source)
        p.scatter(x="timestamp", y="downloaded_pages", fill_alpha=0.6,
                 color=DARK_GRAY, source=self.source)

        hover = p.select(dict(type=HoverTool))
        hover.tooltips = OrderedDict([
            ("harvest_rate", "@harvest_rate"),
        ])

        p.legend.orientation = "top_left"

        script, div = components(p)
        return (script, div) 
Example #24
Source File: app.py    From minimal-flask-example with MIT License 5 votes vote down vote up
def bokehplot():
    figure = make_plot()
    fig_script, fig_div = components(figure)
    return render_template(
        "bokeh.html.j2",
        fig_script=fig_script,
        fig_div=fig_div,
        bkversion=bokeh.__version__,
    ) 
Example #25
Source File: views.py    From memex-explorer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def counts_plot( date, baseline_counts, target_counts ):
    counts_t = np.sum(target_counts)
    counts_b = np.sum(baseline_counts)
    scale_baseline = counts_b >= 10*counts_t
    if scale_baseline:
        baseline_counts *= np.sum(target_counts)/np.sum(baseline_counts)

    plot = figure(x_axis_type = "datetime", plot_height=250, plot_width=600)
    plot.line(date, baseline_counts, legend='Scaled Baseline' if scale_baseline else 'Baseline')
    plot.line(date, target_counts, line_color='orange', legend='Target')
    plot.legend.orientation = "top_left"
    plot.title = 'Counts'

    script, div = components(plot, CDN)
    return { 'script': script, 'div': div } 
Example #26
Source File: plots.py    From cauldron with MIT License 4 votes vote down vote up
def bokeh_plot(
        model,
        scale: float = 0.7,
        responsive: bool = True
) -> str:
    """
    Adds a Bokeh plot object to the notebook display.

    :param model:
        The plot object to be added to the notebook display.
    :param scale:
        How tall the plot should be in the notebook as a fraction of screen
        height. A number between 0.1 and 1.0. The default value is 0.7.
    :param responsive:
        Whether or not the plot should responsively scale to fill the width
        of the notebook. The default is True.
    """
    environ.abort_thread()

    try:
        from bokeh import embed
    except ImportError:
        return templating.render_template(
            template_name='import-error.html',
            library_name='bokeh'
        )

    if responsive:
        model.sizing_mode = "scale_width"
        # model.responsive = True
        model.plot_width = 800
        model.plot_height = round((scale * 9 / 16) * 800)

    results = embed.components(model)

    script = results[0] \
        .split('>', 1)[1] \
        .rsplit('</', 1)[0]

    return templating.render_template(
        'bokeh_component.html',
        script=script,
        dom=results[1],
        scale=round(100 * scale) if scale is not None else 1000
    ) 
Example #27
Source File: csm_reports.py    From edx-load-tests with Apache License 2.0 4 votes vote down vote up
def output_report(outfile, data_source):
    """
    Output a report analyzing a test run.
    """
    all_plots = []
    min_time = None
    max_time = None

    # Generate a single plot for all requests.
    (successes, failures) = data_source.get_req_data(None)
    mins = []
    maxes = []

    if successes:
        mins.append(successes[0]['timestamp'])
        maxes.append(successes[-1]['timestamp'])

    if failures:
        mins.append(failures[0]['timestamp'])
        maxes.append(failures[-1]['timestamp'])

    # Set minimum and maximum times from all request data.
    min_time = min(mins)
    max_time = max(maxes)
    all_plots.append(scatter_plot(
        successes, failures, label='All Requests', min_time=min_time, max_time=max_time
    ))

    # Generate a plot for each request type.
    for req_type in data_source.req_types:
        (successes, failures) = data_source.get_req_data(req_type)
        if len(successes):
            all_plots.append(scatter_plot(
                successes, failures, label=req_type, min_time=min_time, max_time=max_time
            ))

    # Output an HTML report of the test run.
    script, divs = bokeh_components(all_plots)

    try:
        report_template = TEMPLATE_LOOKUP.get_template('test_run_report.html')
        outfile.write(report_template.render(
            script=script,
            divs=divs,
            run_title='CSM Load Test Run: {}'.format(data_source.test_run),
            run_data=data_source.run_data
        ))
    except:
        outfile.write(mako.exceptions.html_error_template().render()) 
Example #28
Source File: dashboard.py    From skein with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def build_html():
    """Build the html, to be served by IndexHandler"""
    source = AjaxDataSource(data_url='./data',
                            polling_interval=INTERVAL,
                            method='GET')

    # OHLC plot
    p = figure(plot_height=400,
               title='OHLC',
               sizing_mode='scale_width',
               tools="xpan,xwheel_zoom,xbox_zoom,reset",
               x_axis_type=None,
               y_axis_location="right",
               y_axis_label="Price ($)")
    p.x_range.follow = "end"
    p.x_range.follow_interval = 100
    p.x_range.range_padding = 0
    p.line(x='time', y='average', alpha=0.25, line_width=3, color='black',
           source=source)
    p.line(x='time', y='ma', alpha=0.8, line_width=2, color='steelblue',
           source=source)
    p.segment(x0='time', y0='low', x1='time', y1='high', line_width=2,
              color='black', source=source)
    p.segment(x0='time', y0='open', x1='time', y1='close', line_width=8,
              color='color', source=source, alpha=0.8)

    # MACD plot
    p2 = figure(plot_height=200,
                title='MACD',
                sizing_mode='scale_width',
                x_range=p.x_range,
                x_axis_label='Time (s)',
                tools="xpan,xwheel_zoom,xbox_zoom,reset",
                y_axis_location="right")
    p2.line(x='time', y='macd', color='darkred', line_width=2, source=source)
    p2.line(x='time', y='macd9', color='navy', line_width=2, source=source)
    p2.segment(x0='time', y0=0, x1='time', y1='macdh', line_width=6, color='steelblue',
               alpha=0.5, source=source)

    # Combine plots together
    plot = gridplot([[p], [p2]], toolbar_location="left", plot_width=1000)

    # Compose html from plots and template
    script, div = components(plot, theme=theme)
    html = template.render(resources=CDN.render(), script=script, div=div)

    return html