Пример #1
0
    def make_source(self):
        self.source = ColumnDataSource(data=self.df)
        self.source.callback = Callback(args=dict(),
                                        code="""

            var inds = cb_obj.get('selected')['1d'].indices;
            var theidx = inds[0];

            console.log("yep");
            console.log(theidx);
            $.get( "reviews", {id: theidx}, function( response ) {
                $( "#section2" ).html( response );
            }, "html");
            console.log("done");
        """)
Пример #2
0
    def make_source(self):
        self.source = ColumnDataSource(data=self.df)
        self.source.callback = Callback(args=dict(),
                                        code="""

            var inds = cb_obj.get('selected')['1d'].indices;
            var theidx = inds[0];
            var d1 = cb_obj.get("data");
            var brand = d1["brand"][theidx];

            console.log("yep");
            console.log(theidx);
            $.get( "shoes", {id: brand}, function( response ) {

                console.log("logging rep");
                console.log(response);
                console.log("done logging rep");
                $( "#child" ).html( response );
            }, "html");
            console.log("done");

        """)

        self.make_brand_source()
Пример #3
0
    def bokeh_plot(self):

        chosen_bic = literal_eval(self.get_argument('subject'))

        # prep
        n_cols = len(chosen_bic['feats'])
        n_lines = len(chosen_bic['objs'])
        bic_mtrx = np.zeros((n_lines, n_cols), dtype=object)

        objs = sorted(chosen_bic['objs'])
        feats = sorted(chosen_bic['feats'])

        # bokeh
        objlist = []
        featlist = []
        # colormap = ["#444444", "#a6cee3", "#1f78b4", "#b2df8a", "#33a02c", "#fb9a99", "#e31a1c", "#fdbf6f", "#ff7f00", "#cab2d6", "#6a3d9a"]
        color = []
        i = 0
        for obj in objs:
            j = 0
            for feat in feats:
                objlist.append(obj)
                featlist.append(feat)
                color.append("#669999")
                #color.append(np.random.choice(colormap))
                bic_mtrx[i, j] = (obj, feat)
                j += 1
            i += 1

        # ColumnDataSource Object
        source = ColumnDataSource(data=dict(xname=objlist,
                                            yname=featlist,
                                            colors=color,
                                            count=bic_mtrx.flatten()))

        source.callback = Callback(args=dict(source=source),
                                   code="""

		var data = source.get('data');
		var f = source.get('value');
		object_p = data['xname'];
		attribute_p = data['yname'];
		document.write(f);

		""")

        p = figure(title="Matriz do Co-Grupo",
                   x_axis_location="above",
                   tools="resize, previewsave, reset, hover",
                   x_range=list(objs),
                   y_range=list(reversed(feats)),
                   plot_width=n_lines * 100,
                   plot_height=n_cols * 40,
                   toolbar_location="left")
        p.rect('xname',
               'yname',
               1,
               1,
               source=source,
               color='colors',
               line_color="#000000")
        p.grid.grid_line_color = None
        p.axis.axis_line_color = None
        p.axis.major_tick_line_color = "#000000"
        p.axis.major_label_text_font_size = "10pt"
        p.axis.major_label_standoff = 0
        p.xaxis.major_label_orientation = np.pi / 2.5
        p.border_fill = "#FFFFF0"
        tap = TapTool(plot=p)
        # tap = TapTool(plot=p, action=OpenURL(url="http://www.ufabc.edu.br"))
        p.tools.append(tap)

        hover = p.select(dict(type=HoverTool))
        hover.tooltips = OrderedDict([('Tupla', '@yname, @xname')])
        # hover = HoverTool(plot=p, tooltips=[('Tupla', '@yname, @xname')])
        # p.tools.append(hover)

        # script & div tags
        script, div = components(p, CDN)

        # return to html
        return (script, div)
def _get_plot():
    years, regions, fertility_df, life_expectancy_df, population_df_size, regions_df = _get_data()

    # Set-up the sources
    sources = {}

    region_color = regions_df['region_color']
    region_color.name = 'region_color'

    for year in years:
        fertility = fertility_df[year]
        fertility.name = 'fertility'
        life = life_expectancy_df[year]
        life.name = 'life'
        population = population_df_size[year]
        population.name = 'population'
        new_df = pd.concat([fertility, life, population, region_color], axis=1)
        sources['_' + str(year)] = ColumnDataSource(new_df)

    dictionary_of_sources = dict(zip([x for x in years], ['_%s' % x for x in years]))
    js_source_array = str(dictionary_of_sources).replace("'", "")

    # Build the plot

    # Set up the plot
    xdr = Range1d(1, 9)
    ydr = Range1d(20, 100)
    plot = Plot(
        x_range=xdr,
        y_range=ydr,
        title="",
        plot_width=800,
        plot_height=400,
        outline_line_color=None,
        toolbar_location=None,
    )
    AXIS_FORMATS = dict(
        minor_tick_in=None,
        minor_tick_out=None,
        major_tick_in=None,
        major_label_text_font_size="10pt",
        major_label_text_font_style="normal",
        axis_label_text_font_size="10pt",

        axis_line_color='#AAAAAA',
        major_tick_line_color='#AAAAAA',
        major_label_text_color='#666666',

        major_tick_line_cap="round",
        axis_line_cap="round",
        axis_line_width=1,
        major_tick_line_width=1,
    )

    xaxis = LinearAxis(SingleIntervalTicker(interval=1), axis_label="Children per woman (total fertility)", **AXIS_FORMATS)
    yaxis = LinearAxis(SingleIntervalTicker(interval=20), axis_label="Life expectancy at birth (years)", **AXIS_FORMATS)
    plot.add_layout(xaxis, 'below')
    plot.add_layout(yaxis, 'left')
    # Add the year in background (add before circle)
    text_source = ColumnDataSource({'year': ['%s' % years[0]]})
    text = Text(x=2, y=35, text='year', text_font_size='150pt', text_color='#EEEEEE')
    plot.add_glyph(text_source, text)
    # Add the circle
    renderer_source = sources['_%s' % years[0]]
    circle_glyph = Circle(
        x='fertility', y='life', size='population',
        fill_color='region_color', fill_alpha=0.8,
        line_color='#7c7e71', line_width=0.5, line_alpha=0.5)
    circle_renderer = plot.add_glyph(renderer_source, circle_glyph)

    # Add the hover (only against the circle and not other plot elements)
    tooltips = "@index"
    plot.add_tools(HoverTool(tooltips=tooltips, renderers=[circle_renderer]))

    text_x = 7
    text_y = 95
    for i, region in enumerate(regions):
        plot.add_glyph(Text(x=text_x, y=text_y, text=[region], text_font_size='10pt', text_color='#666666'))
        plot.add_glyph(Circle(x=text_x - 0.1, y=text_y + 2, fill_color=Spectral6[i], size=10, line_color=None, fill_alpha=0.8))
        text_y = text_y - 5

    # Add the slider
    code = """
        var year = slider.get('value'),
            sources = %s,
            new_source_data = sources[year].get('data');
        renderer_source.set('data', new_source_data);
        renderer_source.trigger('change');
        text_source.set('data', {'year': [String(year)]});
        text_source.trigger('change');
    """ % js_source_array

    callback = Callback(args=sources, code=code)
    slider = Slider(start=years[0], end=years[-1], value=1, step=1, title="Year", callback=callback)
    callback.args["slider"] = slider
    callback.args["renderer_source"] = renderer_source
    callback.args["text_source"] = text_source

    # Lay it out
    return vplot(plot, hplot(slider))
Пример #5
0
cu1_s.callback = Callback(args=dict(cu1_avg=cu1_avg, cu1_lower=cu1_lower, cu1_upper=cu1_upper), code="""
        var inds = cb_obj.get('selected')['1d'].indices;
        var d = cb_obj.get('data');
        var items = [];

        if (inds.length == 0) { return; }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
        for (i = 0; i < inds.length; i++) {
            items.push(d['y'][inds[i]]);
        }

        var ym = average(items);
        var std = standardDeviation(items);

        cu1_avg.get('data')['y'] = [ym, ym]
        cu1_lower.get('data')['y'] = [ym - (2 * std), ym - (2 * std)]
        cu1_upper.get('data')['y'] = [(2 * std) + ym, (2 * std) + ym]

        cb_obj.trigger('change');
        cu1_avg.trigger('change');
        cu1_lower.trigger('change');
        cu1_upper.trigger('change');
    
    	//define the functions needed for standard dev and average
        function standardDeviation(values){
  			var avg = average(values);
  
  			var squareDiffs = values.map(function(value){
    			var diff = value - avg;
    			var sqrDiff = diff * diff;
    			return sqrDiff;
  			});
  
  			var avgSquareDiff = average(squareDiffs);

  			var stdDev = Math.sqrt(avgSquareDiff);
  			return stdDev;
		}

		function average(data){
  			var sum = data.reduce(function(sum, value){
   			 	return sum + value;
 			}, 0);

  			var avg = sum / data.length;
  			return avg;
		}
    """)
Пример #6
0
import numpy as np
import bokeh
from bokeh.models.widgets import Dropdown
from bokeh.io import output_file, show
from bokeh.models import Callback
from bokeh.plotting import figure
from bokeh.layouts import layout

output_file("dropdown.html")

# Dummy plot, otherwise the Dropdown button is partially hidden...
x = np.linspace(-2 * np.pi, 2 * np.pi, 100)
y = np.sin(x)
p = figure(title="Sin(x)", x_axis_label='x', y_axis_label='y')
p.line(x, y)

callback = Callback(args=None,
                    code="""
        console.log(cb_obj)
        var cm_chosen = cb_obj.get('action');
        alert(cm_chosen);
    """)

menu = [("Item %s" % i, "item_%s" % i) for i in range(10)]
dropdown = Dropdown(label="Dropdown button %s" % bokeh.__version__,
                    type="success",
                    menu=menu,
                    callback=callback)

show(layout([dropdown, p]))
           toolbar_location=None,
           title='Hover over points')
p.line(x, y, line_dash="4 4", line_width=1, color='gray')

# Add a circle, that is visible only when selected
source = ColumnDataSource({'x': x, 'y': y})
invisible_circle = Circle(x='x',
                          y='y',
                          fill_color='gray',
                          fill_alpha=0.05,
                          line_color=None,
                          size=20)
visible_circle = Circle(x='x',
                        y='y',
                        fill_color='firebrick',
                        fill_alpha=0.5,
                        line_color=None,
                        size=20)
cr = p.add_glyph(source,
                 invisible_circle,
                 selection_glyph=visible_circle,
                 nonselection_glyph=invisible_circle)

# Add a hover tool, that selects the circle
code = "source.set('selected', cb_data['index']);"
callback = Callback(args={'source': source}, code=code)
p.add_tools(
    HoverTool(tooltips=None, callback=callback, renderers=[cr], mode='hline'))

show(p)
Пример #8
0
# build a dict containing the grouped data
#medals = OrderedDict(bronze=bronze, silver=silver, gold=gold)
medals = OrderedDict(bronze=bronze)

# any of the following commented are also alid Bar inputs
#medals = pd.DataFrame(medals)
#medals = list(medals.values())

output_file("barc.html")

callback = Callback(args=dict(source=bsource), code="""
    var data = source.get('data');
    var f = cb_obj.get('value')
    fac = data['factors']
    ofac = data['ofactors']
    for (i = 0; i < fac.length; i++) {
        fac[i] = ofac[i]
    }
    source.trigger('change');
""")

slider = Slider(start=-2, end=2, value=1, step=.1,
                title="value", callback=callback)

#layout = vform(slider, plot)
layout = vform(slider, p1)

output_file("cb_bar.html", title="callback example")
show(layout)

Пример #9
0
def _get_plot():
    years, regions, fertility_df, life_expectancy_df, population_df_size, regions_df = _get_data(
    )

    # Set-up the sources
    sources = {}

    region_color = regions_df['region_color']
    region_color.name = 'region_color'

    for year in years:
        fertility = fertility_df[year]
        fertility.name = 'fertility'
        life = life_expectancy_df[year]
        life.name = 'life'
        population = population_df_size[year]
        population.name = 'population'
        new_df = pd.concat([fertility, life, population, region_color], axis=1)
        sources['_' + str(year)] = ColumnDataSource(new_df)

    dictionary_of_sources = dict(
        zip([x for x in years], ['_%s' % x for x in years]))
    js_source_array = str(dictionary_of_sources).replace("'", "")

    # Build the plot

    # Set up the plot
    xdr = Range1d(1, 9)
    ydr = Range1d(20, 100)
    plot = Plot(
        x_range=xdr,
        y_range=ydr,
        title="",
        plot_width=800,
        plot_height=400,
        outline_line_color=None,
        toolbar_location=None,
    )
    AXIS_FORMATS = dict(
        minor_tick_in=None,
        minor_tick_out=None,
        major_tick_in=None,
        major_label_text_font_size="10pt",
        major_label_text_font_style="normal",
        axis_label_text_font_size="10pt",
        axis_line_color='#AAAAAA',
        major_tick_line_color='#AAAAAA',
        major_label_text_color='#666666',
        major_tick_line_cap="round",
        axis_line_cap="round",
        axis_line_width=1,
        major_tick_line_width=1,
    )

    xaxis = LinearAxis(SingleIntervalTicker(interval=1),
                       axis_label="Children per woman (total fertility)",
                       **AXIS_FORMATS)
    yaxis = LinearAxis(SingleIntervalTicker(interval=20),
                       axis_label="Life expectancy at birth (years)",
                       **AXIS_FORMATS)
    plot.add_layout(xaxis, 'below')
    plot.add_layout(yaxis, 'left')
    # Add the year in background (add before circle)
    text_source = ColumnDataSource({'year': ['%s' % years[0]]})
    text = Text(x=2,
                y=35,
                text='year',
                text_font_size='150pt',
                text_color='#EEEEEE')
    plot.add_glyph(text_source, text)
    # Add the circle
    renderer_source = sources['_%s' % years[0]]
    circle_glyph = Circle(x='fertility',
                          y='life',
                          size='population',
                          fill_color='region_color',
                          fill_alpha=0.8,
                          line_color='#7c7e71',
                          line_width=0.5,
                          line_alpha=0.5)
    circle_renderer = plot.add_glyph(renderer_source, circle_glyph)

    # Add the hover (only against the circle and not other plot elements)
    tooltips = "@index"
    plot.add_tools(HoverTool(tooltips=tooltips, renderers=[circle_renderer]))

    text_x = 7
    text_y = 95
    for i, region in enumerate(regions):
        plot.add_glyph(
            Text(x=text_x,
                 y=text_y,
                 text=[region],
                 text_font_size='10pt',
                 text_color='#666666'))
        plot.add_glyph(
            Circle(x=text_x - 0.1,
                   y=text_y + 2,
                   fill_color=Spectral6[i],
                   size=10,
                   line_color=None,
                   fill_alpha=0.8))
        text_y = text_y - 5

    # Add the slider
    code = """
        var year = slider.get('value'),
            sources = %s,
            new_source_data = sources[year].get('data');
        renderer_source.set('data', new_source_data);
        renderer_source.trigger('change');
        text_source.set('data', {'year': [String(year)]});
        text_source.trigger('change');
    """ % js_source_array

    callback = Callback(args=sources, code=code)
    slider = Slider(start=years[0],
                    end=years[-1],
                    value=1,
                    step=1,
                    title="Year",
                    callback=callback)
    callback.args["slider"] = slider
    callback.args["renderer_source"] = renderer_source
    callback.args["text_source"] = text_source

    # Lay it out
    return vplot(plot, hplot(slider))
Пример #10
0
from bokeh.plotting import figure, output_file, show

x = list(range(-50, 51))
y = list(x)

source = ColumnDataSource(data=dict(x=x, y=y))

plot = figure(y_range=(-100, 100), plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

callback = Callback(args=dict(source=source),
                    code="""
    var data = source.get('data');
    var f = cb_obj.get('value')
    x = data['x']
    y = data['y']
    for (i = 0; i < x.length; i++) {
        y[i] = f * x[i]
    }
    source.trigger('change');
""")

slider = Slider(start=-2,
                end=2,
                value=1,
                step=.1,
                title="value",
                callback=callback)

layout = vform(slider, plot)
Пример #11
0
output_file("boxselecttool_callback.html")

source = ColumnDataSource(data=dict(x=[], y=[], width=[], height=[]))

callback = Callback(args=dict(source=source), code="""
        // get data source from Callback args
        var data = source.get('data');

        /// get BoxSelectTool dimensions from cb_data parameter of Callback
        var geometry = cb_data['geometry'];

        /// calculate Rect attributes
        var width = geometry['x1'] - geometry['x0'];
        var height = geometry['y1'] - geometry['y0'];
        var x = geometry['x0'] + width/2;
        var y = geometry['y0'] + height/2;

        /// update data source with new Rect attributes
        data['x'].push(x);
        data['y'].push(y);
        data['width'].push(width);
        data['height'].push(height);

        // trigger update of data source
        source.trigger('change');
    """)

box_select = BoxSelectTool(callback=callback)

p = figure(plot_width=400,
           plot_height=400,
Пример #12
0
def make_dashboard(motors, xy_train, operating_earnings, maintenance_cost,
                   repair_cost, run_interval):

    #calculate revenue vs time dataframe
    print '...generating dashboard...'
    events = get_events(motors)
    events['earnings'] = 0.0
    events.loc[events.state == 'operating', 'earnings'] = operating_earnings
    events['expenses'] = 0.0
    events.loc[events.state == 'maintenance', 'expenses'] = maintenance_cost
    events.loc[events.state == 'repair', 'expenses'] = repair_cost
    money = events.groupby('Time').sum()[['earnings', 'expenses']]
    money['revenue'] = money.earnings - money.expenses
    money['cumulative_earnings'] = money.earnings.cumsum()
    money['cumulative_expenses'] = money.expenses.cumsum()
    money['cumulative_revenue'] = money.revenue.cumsum()
    #map the (P,T) decision surface
    T_min = 50
    T_max = 150
    P_min = 0
    P_max = 100
    T_axis = np.arange(T_min, T_max, 0.5)
    P_axis = np.arange(P_min, P_max, 0.5)
    x, y = np.meshgrid(T_axis, P_axis)
    ttf = np.zeros((len(P_axis), len(T_axis)))
    import copy
    m = copy.deepcopy(motors[0])
    for p_idx in np.arange(len(P_axis)):
        for t_idx in np.arange(len(T_axis)):
            m.Temp = T_axis[t_idx]
            m.Pressure = P_axis[p_idx]
            ttf[p_idx, t_idx] = m.predicted_time_to_fail()

    #plot decision surface
    from bokeh.plotting import figure, show, output_file, ColumnDataSource, vplot
    from bokeh.models import HoverTool, Callback
    from bokeh.io import vform
    output_file('dashboard.html', title='Smart Maintenance Dashboard')
    source = ColumnDataSource(data=dict(
        x=xy_train.Temp,
        y=xy_train.Pressure,
        ttf=xy_train.time_to_fail,
        size=0.6 * xy_train.time_to_fail,
    ))
    dec_fig = figure(x_range=[T_min, T_max],
                     y_range=[P_min, P_max],
                     title='SVM Decision Surface',
                     x_axis_label='Temperature',
                     y_axis_label='Pressure',
                     tools='box_zoom,reset,hover,crosshair',
                     width=600,
                     plot_height=600)
    dec_fig.title_text_font_size = '18pt'
    dec_fig.xaxis.axis_label_text_font_size = '14pt'
    dec_fig.yaxis.axis_label_text_font_size = '14pt'
    dec_fig.image(image=[-ttf],
                  x=[T_min],
                  y=[P_min],
                  dw=[T_max - T_min],
                  dh=[P_max - P_min],
                  palette='RdYlGn8')
    dec_fig.x('x',
              'y',
              size='size',
              source=source,
              fill_alpha=0.5,
              fill_color='navy',
              line_color='navy',
              line_width=1,
              line_alpha=0.5)
    hover = dec_fig.select(dict(type=HoverTool))
    hover.tooltips = [
        ("Temperature", "@x"),
        ("Pressure", "@y"),
        ("measured lifetime", "@ttf"),
    ]

    #plot earnings vs time
    source = ColumnDataSource(data=dict(
        t=money.index,
        earnings=money.cumulative_earnings / 1.e6,
        expenses=money.cumulative_expenses / 1.e6,
        revenue=money.cumulative_revenue / 1.e6,
        zero=money.cumulative_revenue * 0,
    ))
    earn_fig = figure(title='Cumulative Earnings & Expenses',
                      x_axis_label='Time',
                      y_axis_label='Earnings & Expenses    (M$)',
                      tools='box_zoom,reset,hover,crosshair',
                      width=1000,
                      plot_height=300,
                      x_range=[0, 1200],
                      y_range=[0, 120])
    earn_fig.title_text_font_size = '15pt'
    earn_fig.xaxis.axis_label_text_font_size = '11pt'
    earn_fig.yaxis.axis_label_text_font_size = '11pt'
    earn_fig.line('t',
                  'earnings',
                  color='blue',
                  source=source,
                  line_width=5,
                  legend='earnings')
    earn_fig.line('t',
                  'expenses',
                  color='red',
                  source=source,
                  line_width=5,
                  legend='expenses')
    earn_fig.legend.orientation = "bottom_right"
    earn_fig.patch([0, 200, 200, 0], [0, 0, 120, 120],
                   color='lightsalmon',
                   alpha=0.35,
                   line_width=0)
    earn_fig.patch([200, 400, 400, 200], [0, 0, 120, 120],
                   color='gold',
                   alpha=0.35,
                   line_width=0)
    earn_fig.patch([400, 1200, 1200, 400], [0, 0, 120, 120],
                   color='darkseagreen',
                   alpha=0.35,
                   line_width=0)
    earn_fig.text([45], [101], ['run-to-fail'])
    earn_fig.text([245], [101], ['scheduled'])
    earn_fig.text([245], [90], ['maintenance'])
    earn_fig.text([445], [101], ['predictive'])
    earn_fig.text([445], [90], ['maintenance'])
    hover = earn_fig.select(dict(type=HoverTool))
    hover.tooltips = [
        ("         Time", "@t"),
        (" earning (M$)", "@earnings"),
        ("expenses (M$)", "@expenses"),
    ]

    #plot revenue vs time
    rev_fig = figure(title='Cumulative Revenue',
                     x_axis_label='Time',
                     y_axis_label='Revenue    (M$)',
                     tools='box_zoom,reset,hover,crosshair',
                     width=1000,
                     plot_height=300,
                     x_range=[0, 1200],
                     y_range=[-15, 10])
    rev_fig.title_text_font_size = '15pt'
    rev_fig.xaxis.axis_label_text_font_size = '11pt'
    rev_fig.yaxis.axis_label_text_font_size = '11pt'
    rev_fig.line('t',
                 'revenue',
                 color='green',
                 source=source,
                 line_width=5,
                 legend='revenue')
    rev_fig.line('t',
                 'zero',
                 color='purple',
                 source=source,
                 line_width=3,
                 alpha=0.5,
                 line_dash=[10, 5])
    rev_fig.legend.orientation = "bottom_right"
    rev_fig.patch([0, 200, 200, 0], [-15, -15, 10, 10],
                  color='lightsalmon',
                  alpha=0.35,
                  line_width=0)
    rev_fig.patch([200, 400, 400, 200], [-15, -15, 10, 10],
                  color='gold',
                  alpha=0.35,
                  line_width=0)
    rev_fig.patch([400, 1200, 1200, 400], [-15, -15, 10, 10],
                  color='darkseagreen',
                  alpha=0.35,
                  line_width=0)
    hover = rev_fig.select(dict(type=HoverTool))
    hover.tooltips = [
        ("         Time", "@t"),
        (" revenue (M$)", "@revenue"),
    ]

    #plot number of motors vs time
    N = events.groupby(['Time', 'state']).count().unstack()['id'].reset_index()
    N.fillna(value=0, inplace=True)
    N['total'] = N.maintenance + N.operating + N.repair
    s1 = ColumnDataSource(data=dict(
        Time=N.Time,
        operating=N.operating,
        maintenance=N.maintenance,
        repair=N.repair,
        total=N.total,
    ))
    motor_fig = figure(title='Number of Motors',
                       x_axis_label='Time',
                       y_axis_label='Number of motors',
                       tools='box_zoom,reset,hover,crosshair',
                       width=1000,
                       plot_height=300,
                       x_range=[0, 1200],
                       y_range=[-10, 210])
    motor_fig.title_text_font_size = '15pt'
    motor_fig.xaxis.axis_label_text_font_size = '11pt'
    motor_fig.yaxis.axis_label_text_font_size = '11pt'
    motor_fig.line('Time',
                   'total',
                   color='blue',
                   source=s1,
                   line_width=3,
                   legend='total')
    motor_fig.line('Time',
                   'operating',
                   color='green',
                   source=s1,
                   line_width=3,
                   legend='operating')
    motor_fig.line('Time',
                   'maintenance',
                   color='orange',
                   source=s1,
                   line_width=3,
                   legend='maintenance')
    motor_fig.line('Time',
                   'repair',
                   color='red',
                   source=s1,
                   line_width=3,
                   legend='repair')
    motor_fig.legend.orientation = "top_right"
    motor_fig.patch([0, 200, 200, 0], [-10, -10, 210, 210],
                    color='lightsalmon',
                    alpha=0.35,
                    line_width=0)
    motor_fig.patch([200, 400, 400, 200], [-10, -10, 210, 210],
                    color='gold',
                    alpha=0.35,
                    line_width=0)
    motor_fig.patch([400, 1200, 1200, 400], [-10, -10, 210, 210],
                    color='darkseagreen',
                    alpha=0.35,
                    line_width=0)

    #display N table
    from bokeh.models.widgets import DataTable, TableColumn
    from bokeh.io import vform
    columns = [
        TableColumn(field='Time', title='Time'),
        TableColumn(field='operating', title='operating'),
        TableColumn(field='maintenance', title='maintenance'),
        TableColumn(field='repair', title='repair'),
        TableColumn(field='total', title='total'),
    ]
    s2 = s1.clone()
    N_table = DataTable(source=s2, columns=columns, width=600, height=300)
    s1.callback = Callback(args=dict(s2=s2),
                           code="""
        var inds = cb_obj.get('selected')['1d'].indices;
        var d1 = cb_obj.get('data');
        var d2 = s2.get('data');
        d2['Time'] = []
        d2['operating'] = []
        d2['maintenance'] = []
        d2['repair'] = []
        d2['total'] = []
        for (i = 0; i < inds.length; i++) {
            d2['Time'].push(d1['Time'][inds[i]])
            d2['operating'].push(d1['operating'][inds[i]])
            d2['maintenance'].push(d1['maintenance'][inds[i]])
            d2['repair'].push(d1['repair'][inds[i]])
            d2['total'].push(d1['total'][inds[i]])
        }
        s2.trigger('change');
    """)

    #export plot to html and return
    plot_grid = vplot(dec_fig, earn_fig, rev_fig, motor_fig, vform(N_table))
    show(plot_grid, new='tab')
    return money, events, N
Пример #13
0
    """

p1 = figure(title='Pan and Zoom Here',
            x_range=(0, 100),
            y_range=(0, 100),
            tools='box_zoom,wheel_zoom,pan,reset',
            plot_width=400,
            plot_height=400)
p1.scatter(x,
           y,
           radius=radii,
           fill_color=colors,
           fill_alpha=0.6,
           line_color=None)

p1.x_range.callback = Callback(args=dict(source=source, range=p1.x_range),
                               code=jscode % ('x', 'width'))
p1.y_range.callback = Callback(args=dict(source=source, range=p1.y_range),
                               code=jscode % ('y', 'height'))

p2 = figure(title='See Zoom Window Here',
            x_range=(0, 100),
            y_range=(0, 100),
            tools='',
            plot_width=400,
            plot_height=400)
p2.scatter(x,
           y,
           radius=radii,
           fill_color=colors,
           fill_alpha=0.6,
           line_color=None)
Пример #14
0
           tools="lasso_select",
           title="Select Here")
p.circle('x', 'y', color='color', size=8, source=s, alpha=0.4)

s2 = ColumnDataSource(data=dict(ym=[0.5, 0.5]))
p.line(x=[0, 1], y='ym', color="orange", line_width=5, alpha=0.6, source=s2)

s.callback = Callback(args=dict(s2=s2),
                      code="""
        var inds = cb_obj.get('selected')['1d'].indices;
        var d = cb_obj.get('data');
        var ym = 0

        if (inds.length == 0) { return; }

        for (i = 0; i < d['color'].length; i++) {
            d['color'][i] = "navy"
        }
        for (i = 0; i < inds.length; i++) {
            d['color'][inds[i]] = "firebrick"
            ym += d['y'][inds[i]]
        }

        ym /= inds.length
        s2.get('data')['ym'] = [ym, ym]

        cb_obj.trigger('change');
        s2.trigger('change');
    """)

show(p)
Пример #15
0
callback = Callback(args=dict(source=source),
                    code="""
    var data = source.get('data');
    var f = cb_obj.get('value')
    fill = data['fill_color']
    allc = data['all_color']
    fc = data['first_color']
    sc = data['second_color']
    tc = data['third_color']
    foc = data['fourth_color']
    if (f == 4) {
        for (i = 0; i < fill.length; i++) {
            fill[i] = allc[i]
        }
    }
    if (f == 3) {
        for (i = 0; i < fill.length; i++) {
            fill[i] = fc[i]
        }
    }
    if (f == 2) {
        for (i = 0; i < fill.length; i++) {
            fill[i] = sc[i]
        }
    }
    if (f == 1) {
        for (i = 0; i < fill.length; i++) {
            fill[i] = tc[i]
        }
    }
    if (f == 0) {
        for (i = 0; i < fill.length; i++) {
            fill[i] = foc[i]
        }
    }
    source.trigger('change');
""")
#First plot
s1 = ColumnDataSource(data=dict(x=x, y=y))
p1 = figure(tools=["lasso_select"], plot_width=600, plot_height=400)
p1.scatter('x', 'y', fill_color='black', line_color=None, size=10, source=s1)

#Second plot
s2 = ColumnDataSource(data=dict(x=[], y=[], y2=[]))
p2 = figure(plot_width=400, plot_height=400, tools=[])

m1 = ColumnDataSource(m1)  #Actual Datasource for the second plot
p2.line(np.arange(0, 100, 1), 'y', source=s2)  # From original data - series 1
p2.line(np.arange(0, 100, 1), 'y2', source=s2)  # From original data - series 2

s1.callback = Callback(args=dict(s2=s2, m1=m1),
                       code="""
  var inds = cb_obj.get('selected')['1d'].indices;
  var d1 = m1.get('data'); 
  var d2 = s2.get('data');
  d2['y'] = []
  d2['y2'] = []
  for (i = 0; i < 11; i++) {o
    d2['y'].push(d1[inds['0']][i]),
    d2['y2'].push(d1[inds['1']][i])
  }
  s2.trigger('change'); 
""")

layout = hplot(p1, p2)
show(layout)
output_file("callback.html")

x = [random() for x in range(500)]
y = [random() for y in range(500)]

s1 = ColumnDataSource(data=dict(x=x, y=y))
p1 = figure(plot_width=400, plot_height=400, tools="lasso_select", title="Select Here")
p1.circle('x', 'y', source=s1, alpha=0.6)

s2 = ColumnDataSource(data=dict(x=[], y=[]))
p2 = figure(plot_width=400, plot_height=400, x_range=(0, 1), y_range=(0, 1),
            tools="", title="Watch Here")
p2.circle('x', 'y', source=s2, alpha=0.6)

s1.callback = Callback(args=dict(s2=s2), code="""
        var inds = cb_obj.get('selected')['1d'].indices;
        var d1 = cb_obj.get('data');
        var d2 = s2.get('data');
        d2['x'] = []
        d2['y'] = []
        for (i = 0; i < inds.length; i++) {
            d2['x'].push(d1['x'][inds[i]])
            d2['y'].push(d1['y'][inds[i]])
        }
        s2.trigger('change');
    """)

layout = hplot(p1, p2)

show(layout)
Пример #18
0
def build_map(data, variables, years=None, plot_width=800,
                         x_range=[70, 140], y_range=[10, 60], title=""):
    #aspect_ratio = (x_range[1] - x_range[0]) / (y_range[1] - y_range[0])
    #plot_height = int(plot_width / aspect_ratio)
    plot_height = plot_width
    x_range = Range1d(x_range[0], x_range[1])
    y_range = Range1d(y_range[0], y_range[1])

    plot = Plot(
        x_range=x_range,
        y_range=y_range,
        title=title,
        plot_width=plot_width,
        plot_height=plot_height,
        **PLOT_FORMATS)

    if years is None:
        tt_year = '—'
        tt_var = variables[0]
        color_column = '{}_color'.format(variables[0])
    else:
        tt_year = '@active_year'
        tt_var = 'active_value'
        color_column = 'active_color'
    tooltip = """<span class='tooltip-text year'>{}</span>
        <span class='tooltip-text country'>@alpha @name_zh @name_en</span>
        <span class='tooltip-text value'>@{}</span>""".format(tt_year, tt_var)
    plot.add_tools(HoverTool(tooltips=tooltip))

    source = ColumnDataSource(data)

    countries = Patches(
        xs='xs',
        ys='ys',
        fill_color=color_column,
        line_color='#000000'
        )

    renderer = plot.add_glyph(source, countries)

    if years is None:
        return plot

    callback = Callback(code="""
        var year = select.get('value');
        var data = source.get('data');
        var i = %d;
        data['active_color'] = data[year + '_color'];
        data['active_value'] = data[year];
        while (--i >= 0) {
            // Instead of doing this I'd like to
            // be able to change the hover tool
            data['active_year'][i] = year;
        }
        source.trigger('change');
        """ % len(years))
    select = Select(title="Year", options=years, value=years[-1],
                    callback=callback)
    callback.args = {
        'select': select,
        'source': source
        }

    layout = vplot(select, plot)

    return layout