Ejemplo n.º 1
0
def make_layout():
    plot, source = make_plot()
    columns = [
        TableColumn(field="dates", title="Date", editor=DateEditor(), formatter=DateFormatter()),
        TableColumn(field="downloads", title="Downloads", editor=IntEditor()),
    ]
    data_table = DataTable(source=source, columns=columns, width=400, height=400, editable=True)
    button = Button(label="Randomize data", type="success")
    button.on_click(click_handler)
    buttons = VBox(children=[button])
    vbox = VBox(children=[buttons, plot, data_table])
    return vbox
Ejemplo n.º 2
0
    def add_plot(self, new_plot, linked_x_axis=True):
        self.document.clear()
        new_plot.x_range.bounds = None
        new_plot.y_range.bounds = None
        for key, plot in enumerate(self.plots):
            if new_plot.title == plot.title:
                self.plots.pop(key)
                self.plots.append(new_plot)
                break
        else:
            self.plots.append(new_plot)
        if linked_x_axis:
            for plot in self.plots[1:]:
                plot.x_range = self.plots[0].x_range
                plot.x_range.bounds = None
                plot.y_range.bounds = None

        if len(self.plots) > 1:
            number_of_rows = int(round(len(self.plots) / 2))
            rows = []
            number_of_columns = 2
            i = 0
            for each in range(number_of_rows):
                rows.append(
                    list(plot for plot in self.plots[i:i + number_of_columns]))
                i += number_of_columns
            layout = gridplot(rows)
        else:
            print('Layout...')
            layout = VBox(children=self.plots)

        self.document.add_root(layout)
Ejemplo n.º 3
0
def plot(title): 
    with open('12.txt', 'r') as f:
        data = f.read()
    a1 = [int(x) for x in re.findall('(\d*) \d* .*', data)]
    a2 = [int(x) for x in re.findall('\d* (\d*) .*', data)]
    times = [float(x) for x in re.findall('\d* \d* (.*)', data)]
    df = pd.DataFrame({'proc':a1, 'thread':a2, 'time':times})
    df.sort_values(['proc'], ascending=[1], inplace=True)
    xs = ['({},{})'.format(x,y) for x,y in zip(df['proc'], df['thread'])]
    p1 = figure(x_range=xs)
    p1.line(xs, df['time'], line_width=2)
    p1.circle(xs, df['time'], size=4)
    p1.xaxis.axis_label = '#proc'
    p1.yaxis.axis_label = 'time(s)'
    
    with open('all.txt', 'r') as f:
        data = f.read()
    a1 = [int(x) for x in re.findall('(\d*) \d* .*', data)]
    a2 = [int(x) for x in re.findall('\d* (\d*) .*', data)]
    xs = [x*y for x,y in zip(a1,a2)]
    times = [float(x) for x in re.findall('\d* \d* (.*)', data)]
    df = pd.DataFrame({'proc':a1, 'thread':a2, 'xs':xs, 'time':times})
    df.sort_values(['xs', 'proc'], ascending=[1,1], inplace=True)
    xs = ['({},{})'.format(x,y) for x,y in zip(df['proc'], df['thread'])]
    p2 = figure(x_range=xs)
    p2.line(xs, df['time'], line_width=2)
    p2.circle(xs, df['time'], size=4)
    p2.xaxis.axis_label = '#proc'
    p2.yaxis.axis_label = 'time(s)'
    p = VBox(p1, p2)
    output_file('best.html')
    save(p)
Ejemplo n.º 4
0
def create_layout():
    year_select = Select(title="Year:", value="2010", options=years)
    location_select = Select(title="Location:",
                             value="World",
                             options=locations)

    year_select.on_change('value', on_year_change)
    location_select.on_change('value', on_location_change)

    controls = HBox(children=[year_select, location_select])
    layout = VBox(children=[controls, pyramid(), population()])

    return layout
Ejemplo n.º 5
0
def large_plot(n):
    from bokeh.models import (Plot, LinearAxis, Grid, GlyphRenderer,
                              ColumnDataSource, DataRange1d, PanTool,
                              ZoomInTool, ZoomOutTool, WheelZoomTool,
                              BoxZoomTool, BoxSelectTool, ResizeTool, SaveTool,
                              ResetTool)
    from bokeh.models.layouts import VBox
    from bokeh.models.glyphs import Line

    vbox = VBox()
    objects = set([vbox])

    for i in xrange(n):
        source = ColumnDataSource(data=dict(x=[0, i + 1], y=[0, i + 1]))
        xdr = DataRange1d()
        ydr = DataRange1d()
        plot = Plot(x_range=xdr, y_range=ydr)
        xaxis = LinearAxis(plot=plot)
        yaxis = LinearAxis(plot=plot)
        xgrid = Grid(plot=plot, dimension=0)
        ygrid = Grid(plot=plot, dimension=1)
        tickers = [
            xaxis.ticker, xaxis.formatter, yaxis.ticker, yaxis.formatter
        ]
        glyph = Line(x='x', y='y')
        renderer = GlyphRenderer(data_source=source, glyph=glyph)
        plot.renderers.append(renderer)
        pan = PanTool()
        zoom_in = ZoomInTool()
        zoom_out = ZoomOutTool()
        wheel_zoom = WheelZoomTool()
        box_zoom = BoxZoomTool()
        box_select = BoxSelectTool()
        resize = ResizeTool()
        save = SaveTool()
        reset = ResetTool()
        tools = [
            pan, zoom_in, zoom_out, wheel_zoom, box_zoom, box_select, resize,
            save, reset
        ]
        plot.add_tools(*tools)
        vbox.children.append(plot)
        objects |= set([
            source, xdr, ydr, plot, xaxis, yaxis, xgrid, ygrid, renderer,
            glyph, plot.toolbar, plot.tool_events, plot.title,
            box_zoom.overlay, box_select.overlay
        ] + tickers + tools)

    return vbox, objects
Ejemplo n.º 6
0
def check_children_prop(layout_callable):
    ## component subclasses are layouts, widgets and plots
    components = [HBox(), VBox(), Figure()]

    # Test layout accepts splatted components
    layout1 = layout_callable(*components)
    assert layout1.children == components

    # Test layout accepts children argument
    layout2 = layout_callable(children=components)
    assert layout2.children == components

    # Test value error raised when non-layout is provided as children
    with pytest.raises(ValueError):
        layout_callable(children=[ColumnDataSource()])
Ejemplo n.º 7
0
def plot():
    p1 = figure(title='#points')
    p2 = figure(title='execution time')
    eps = [[0, 0.15], [0.35, 0.45], [0.65, 0.75]]
    colors = [['greenyellow', 'darkgreen'], ['lightblue', 'darkblue'],
              ['pink', 'red']]
    for c0, ver in zip(range(3), ['MPI', 'OpenMP', 'Hybrid']):
        for c1, tp in zip(range(3), ['static', 'dynamic']):
            with open('MS_{}_{}_load.out'.format(ver, tp), 'r') as f:
                data = f.read()
            ids = [int(x) for x in re.findall('\[(\d*)\] \d* \d*.\d*', data)]
            pts = [int(x) for x in re.findall('\[\d*\] (\d*) \d*.\d*', data)]
            times = [
                float(x) for x in re.findall('\[\d*\] \d* (\d*.\d*)', data)
            ]
            df = pd.DataFrame({'id': ids, 'point': pts, 'time': times})
            df.sort_values(['id'], ascending=[1], inplace=True)
            for idx, row in df.iterrows():
                p1.line([row['id'] + eps[c0][c1], row['id'] + eps[c0][c1]],
                        [0, row['point']],
                        legend='{}-{}'.format(ver, tp),
                        line_color=colors[c0][c1],
                        line_width=4)
                p1.circle([row['id'] + eps[c0][c1]], [row['point']],
                          color=colors[c0][c1],
                          size=5)
                p2.line([row['id'] + eps[c0][c1], row['id'] + eps[c0][c1]],
                        [0, row['time']],
                        legend='{}-{}'.format(ver, tp),
                        line_color=colors[c0][c1],
                        line_width=4)
                p2.circle([row['id'] + eps[c0][c1]], [row['time']],
                          color=colors[c0][c1],
                          size=5)
    p1.xaxis.axis_label = 'thread-ID / MPI_Task-ID'
    p1.yaxis.axis_label = '#points'
    p2.xaxis.axis_label = 'thread-ID / MPI_Task-ID'
    p2.yaxis.axis_label = 'execution time(s)'
    p = VBox(p1, p2)
    output_file('load.html')
    save(p)
Ejemplo n.º 8
0
def test_VBox():
    check_props(VBox())
    check_children_prop(VBox)
    check_widget_wrapped_in_widget_box(VBox)
                for(j = 0; j < count.length; j++){
                    if (num == 0){
                        temp = 0;
                    }else{
                        temp = count[j];
                    }
                    count[j] = temp + data1[careerarea_selector_name][j];
                }
            }
        }
        source1.trigger('change');
        source2.trigger('change');
    """)

######################################################
#Deploy widget, call back
######################################################
career_area_bar.add_tools(TapTool(renderers=[bar], callback=callback_career))

select_experience = Select(
    title="Select postings that require experience of:",
    value='All',
    options=['All', 'None', 'At least 1 year', 'At least 2 year'],
    callback=callback_experience)

#Display data
multi_filter = VBox(widgetbox(select_experience), career_area_bar)
tot = HBox(multi_filter, gridplot([[mp]]))

show(tot)
Ejemplo n.º 10
0
    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

    plot.add_tools(HoverTool())

    tab = Panel(child=plot, title=title)

    return tab


def make_tabs(objs):
    return Tabs(tabs=[make_tab(title, obj) for title, obj in objs])


layout = VBox(children=[
    Paragraph(text="Only Image and ImageRGBA glyphs are not demonstrated."),
    make_tabs(glyphs),
    make_tabs(markers)
])

doc = Document()
doc.add_root(layout)

if __name__ == "__main__":
    filename = "glyphs.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Glyphs"))
    print("Wrote %s" % filename)
    view(filename)
Ejemplo n.º 11
0
def templateAcceptedLoanPerRegion():
    LABELS = ["Central", "Mid - Atlantic", "NorthEast", "NorthWest", "South", "SouthEast", "SouthWest"]
    colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#17becf']
    data = pd.read_csv(DATA + 'perc_acc_loan_per_region_date_compact.csv')

    central = data['Central'] / 100
    midatl = data['Mid-Atlantic'] / 100
    northe = data['Northeast'] / 100
    northw = data['Northwest'] / 100
    south = data['South'] / 100
    southe = data['Southeast'] / 100
    southw = data['Southwest'] / 100
    date = data['date']

    source = ColumnDataSource(data=dict(x=[datetime.strptime(d, '%b-%Y') for d in date.values],
                                        Central=central,
                                        MidAtlantic=midatl,
                                        Northeast=northe,
                                        Northwest=northw,
                                        South=south,
                                        Southeast=southe,
                                        Southwest=southw
                                        ))

    props = dict(line_width=4, line_alpha=0.8)
    p = Figure(x_axis_type="datetime", width=1200, height=380)
    p0 = p.line('x', 'Central', source=source, legend="Central", line_color=colors[0], **props)
    p1 = p.line('x', 'MidAtlantic', source=source, legend="Mid - Atlantic", line_color=colors[1], **props)
    p2 = p.line('x', 'Northeast', source=source, legend="NorthEast", line_color=colors[2], **props)
    p3 = p.line('x', 'Northwest', source=source, legend="NorthWest", line_color=colors[3], **props)
    p4 = p.line('x', 'South', source=source, legend="South", line_color=colors[4], **props)
    p5 = p.line('x', 'Southeast', source=source, legend="SouthEast", line_color=colors[5], **props)
    p6 = p.line('x', 'Southwest', source=source, legend="SouthWest", line_color=colors[6], **props)

    p.yaxis.axis_label = 'Percentage of accepted loans'
    p.yaxis[0].formatter = NumeralTickFormatter(format="0.0%")
    p.border_fill_color = LIGHT_GREEN
    p.background_fill_color = LIGHT_GREEN
    p.legend.background_fill_color = LIGHT_GREEN
    p.legend.background_fill_alpha = 0.5

    checkbox = CheckboxGroup(
        labels=LABELS,
        inline=True,
        active=[0, 1, 2, 3, 4, 5, 6],
        width=800)

    code = """
        //console.log(cb_obj.active);
        p0.visible = false;
        p1.visible = false;
        p2.visible = false;
        p3.visible = false;
        p4.visible = false;
        p5.visible = false;
        p6.visible = false;

        for (i in checkbox.active) {
            //console.log(cb_obj.active[i]);
            if (checkbox.active[i] == 0) {
                p0.visible = true;
            } else if (checkbox.active[i] == 1) {
                p1.visible = true;
            } else if (checkbox.active[i] == 2) {
                p2.visible = true;
            } else if (checkbox.active[i] == 3) {
                p3.visible = true;
            } else if (checkbox.active[i] == 4) {
                p4.visible = true;
            } else if (checkbox.active[i] == 5) {
                p5.visible = true;
            } else if (checkbox.active[i] == 6) {
                p6.visible = true;
            }
        }
    """

    checkbox.callback = CustomJS(args=dict(p0=p0, p1=p1, p2=p2, p3=p3, p4=p4, p5=p5, p6=p6, checkbox=checkbox),
                                 code=code)

    boundaries = open(DATA + 'boundaries.json').read()
    states = json.loads(boundaries)
    region_state = pd.read_csv(DATA + 'region-state.csv', header=0)
    region_state = region_state.set_index('state')

    state_xs = [states[code]["lons"] for code in states]
    state_ys = [states[code]["lats"] for code in states]
    name = states.keys()

    colors_state = []

    for i in name:
        if i != 'AK' and i != 'HI':
            reg = region_state.loc[i]['region']
            if reg == "Central":
                colors_state.append(colors[0])
            elif reg == "Mid-Atlantic":
                colors_state.append(colors[1])
            elif reg == "Northeast":
                colors_state.append(colors[2])
            elif reg == "Northwest":
                colors_state.append(colors[3])
            elif reg == "South":
                colors_state.append(colors[4])
            elif reg == "Southeast":
                colors_state.append(colors[5])
            elif reg == "Southwest":
                colors_state.append(colors[6])

    source = ColumnDataSource(data=dict(
        x=state_xs,
        y=state_ys,
        name=name,
        colors=colors_state,
    ))

    q = figure(title="",
               toolbar_location=None,
               plot_width=300,
               plot_height=160
               )
    q.xaxis.visible = False
    q.yaxis.visible = False
    q.xgrid.grid_line_color = None
    q.ygrid.grid_line_color = None
    q.min_border_left = False
    q.min_border_right = False
    q.min_border_top = False
    q.min_border_bottom = False
    q.border_fill_color = LIGHT_GREEN
    q.background_fill_color = LIGHT_GREEN

    q.patches('x', 'y', source=source,
              fill_color='colors',
              fill_alpha=0.9, line_color="white", line_width=0.1)

    layout = VBox(q, checkbox, p)

    # show(layout)

    script, div = components(layout)

    return script, div
Ejemplo n.º 12
0
'''
Created on 29 May 2017

@author: jermz
'''
from bokeh.plotting import Figure
from bokeh.models.layouts import VBox
from bokeh.models.widgets import RadioGroup
from bokeh.io import curdoc

fig1 = Figure()
fig1.circle(x=[1,2], y=[3,4])

fig2 = Figure()
fig2.circle(x=[100,200], y=[200, 1000])

def switch_plots(selected_plot):
    main_box.children = layouts[selected_plot]

layout_picker = RadioGroup(labels=['Layout1', 'Layout2'])
layout_picker.on_click(switch_plots)

layout1 = VBox(children=[fig1])
layout2 = VBox(children=[fig2])
layouts = [[layout1], [layout2]]

main_box = VBox(children=[layout1])

curdoc().add_root(main_box)
curdoc().add_root(layout_picker)
Ejemplo n.º 13
0
menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")]
dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu)
dropdown.on_click(dropdown_handler)

menu = [("Item 1", "foo"), ("Item 2", "bar"), None, ("Item 3", "baz")]
split = Dropdown(label="Split button", button_type="danger", menu=menu, default_value="baz")
split.on_click(split_handler)

checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_group.on_click(checkbox_group_handler)

radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_group.on_click(radio_group_handler)

checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
checkbox_button_group.on_click(checkbox_button_group_handler)

radio_button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
radio_button_group.on_click(radio_button_group_handler)

vbox = VBox(children=[button, toggle, dropdown, split, checkbox_group, radio_group, checkbox_button_group, radio_button_group])

document = Document()
document.add_root(vbox)
session = push_session(document)
session.show()

if __name__ == "__main__":
    session.loop_until_closed()
Ejemplo n.º 14
0
def plotall(data,
            circleinds=[],
            crossinds=[],
            edgeinds=[],
            htmlname=None,
            noiseplot=None,
            url_path='plots',
            fileroot=None):
    """ Create interactive plot (preserving links between panels) from data dictionary

    data has keys of snr, time, dm, sizes, key and more.
    Optional index arguments are used to filter full data set.
    This can be used to remove bad segments or apply different symbols to subsets.
    url_path is path difference to png files for taptool. ('../plots' for jupyter notebook, 'plots' for public page)
    fileroot is the sdm file name used as root for all png files.
    """

    # set up data dictionary
    if not circleinds: circleinds = calcinds(data, np.abs(data['snrs']).min())
    if not crossinds:
        crossinds = calcinds(data, -1 * np.abs(data['snrs']).min())

    TOOLS = "hover,tap,pan,box_select,wheel_zoom,reset"

    # set ranges
    datalen = len(data['dm'])
    inds = circleinds + crossinds + edgeinds
    dm = [data['dm'][i] for i in inds]
    dm_min = min(min(dm), max(dm) / 1.2)
    dm_max = max(max(dm), min(dm) * 1.2)
    time = [data['time'][i] for i in inds]
    time_min = min(time)
    time_max = max(time)
    l1 = [data['l1'][i] for i in inds]
    l1_min = min(l1)
    l1_max = max(l1)
    m1 = [data['m1'][i] for i in inds]
    m1_min = min(m1)
    m1_max = max(m1)
    specstd = [data['specstd'][i] for i in inds]
    specstd_min = min(specstd)
    specstd_max = max(specstd)
    imkur = [data['imkur'][i] for i in inds]
    imkur_min = min(imkur)
    imkur_max = max(imkur)

    # create figures
    dmt = Figure(plot_width=950,
                 plot_height=500,
                 toolbar_location="left",
                 x_axis_label='Time (s; relative)',
                 y_axis_label='DM (pc/cm3)',
                 x_range=(time_min, time_max),
                 y_range=(dm_min, dm_max),
                 webgl=True,
                 tools=TOOLS)
    loc = Figure(plot_width=450,
                 plot_height=400,
                 toolbar_location="left",
                 x_axis_label='l1 (rad)',
                 y_axis_label='m1 (rad)',
                 x_range=(l1_min, l1_max),
                 y_range=(m1_min, m1_max),
                 tools=TOOLS,
                 webgl=True)
    stat = Figure(plot_width=450,
                  plot_height=400,
                  toolbar_location="left",
                  x_axis_label='Spectral std',
                  y_axis_label='Image kurtosis',
                  x_range=(specstd_min, specstd_max),
                  y_range=(imkur_min, imkur_max),
                  tools=TOOLS,
                  webgl=True)
    norm = Figure(plot_width=450,
                  plot_height=400,
                  toolbar_location="left",
                  x_axis_label='SNR observed',
                  y_axis_label='SNR expected',
                  tools=TOOLS,
                  webgl=True)

    # create positive symbol source and add glyphs
    source = ColumnDataSource(
        data=dict({(key,
                    tuple([value[i] for i in circleinds if i not in edgeinds]))
                   for (key, value) in data.iteritems()}))
    dmt.circle('time',
               'dm',
               size='sizes',
               fill_color='colors',
               line_color=None,
               fill_alpha=0.2,
               source=source)
    loc.circle('l1',
               'm1',
               size='sizes',
               line_color=None,
               fill_color='colors',
               fill_alpha=0.2,
               source=source)
    stat.circle('specstd',
                'imkur',
                size='sizes',
                line_color=None,
                fill_color='colors',
                fill_alpha=0.2,
                source=source)
    norm.circle('abssnr',
                'zs',
                size='sizes',
                line_color=None,
                fill_color='colors',
                fill_alpha=0.2,
                source=source)

    # create negative symbol source and add glyphs
    if crossinds:
        sourceneg = ColumnDataSource(
            data=dict({(key, tuple([value[i] for i in crossinds]))
                       for (key, value) in data.iteritems()}))
        dmt.cross('time',
                  'dm',
                  size='sizes',
                  fill_color='colors',
                  line_alpha=0.3,
                  source=sourceneg)
        loc.cross('l1',
                  'm1',
                  size='sizes',
                  line_color='colors',
                  line_alpha=0.3,
                  source=sourceneg)
        stat.cross('specstd',
                   'imkur',
                   size='sizes',
                   line_color='colors',
                   line_alpha=0.3,
                   source=sourceneg)
        norm.cross('abssnr',
                   'zs',
                   size='sizes',
                   line_color='colors',
                   line_alpha=0.3,
                   source=sourceneg)

    # create linked symbol source and add glyphs
    if edgeinds:
        sourceedge = ColumnDataSource(
            data=dict({(key, tuple([value[i] for i in edgeinds]))
                       for (key, value) in data.iteritems()}))
        dmt.circle('time',
                   'dm',
                   size='sizes',
                   line_color='colors',
                   fill_color='colors',
                   line_alpha=0.5,
                   fill_alpha=0.2,
                   source=sourceedge)
        loc.circle('l1',
                   'm1',
                   size='sizes',
                   line_color='colors',
                   fill_color='colors',
                   source=sourceedge,
                   line_alpha=0.5,
                   fill_alpha=0.2)
        stat.circle('specstd',
                    'imkur',
                    size='sizes',
                    line_color='colors',
                    fill_color='colors',
                    source=sourceedge,
                    line_alpha=0.5,
                    fill_alpha=0.2)
        norm.circle('abssnr',
                    'zs',
                    size='sizes',
                    line_color='colors',
                    fill_color='colors',
                    source=sourceedge,
                    line_alpha=0.5,
                    fill_alpha=0.2)

    hover = dmt.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])
    hover = loc.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])
    hover = stat.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])
    hover = norm.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([('SNR', '@snrs'), ('key', '@key')])

    if url_path and fileroot:
        url = '{}/cands_{}[email protected]'.format(url_path, fileroot)
        taptool = dmt.select(type=TapTool)
        taptool.callback = OpenURL(url=url)
        taptool = loc.select(type=TapTool)
        taptool.callback = OpenURL(url=url)
        taptool = stat.select(type=TapTool)
        taptool.callback = OpenURL(url=url)
        taptool = norm.select(type=TapTool)
        taptool.callback = OpenURL(url=url)


# this approach does not preserve links between panels
#    dmt = plotdmt(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds, url_path=url_path, fileroot=fileroot, tools=TOOLS) # maybe add size?
#    loc = plotloc(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds, url_path=url_path, fileroot=fileroot, tools=TOOLS)
#    stat = plotstat(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds, url_path=url_path, fileroot=fileroot, tools=TOOLS)
#    norm = plotnorm(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds, url_path=url_path, fileroot=fileroot, tools=TOOLS)

# arrange figures
    top = HBox(dmt, width=950)
    middle = HBox(loc, stat, width=950)
    if noiseplot:
        bottom = HBox(norm, noiseplot, width=950)
    else:
        bottom = HBox(norm, width=950)
    combined = VBox(top, middle, bottom, width=950)

    if htmlname:
        output_file(htmlname)
        save(combined)
    else:
        return combined
Ejemplo n.º 15
0

def on_text_value_change(attr, old, new):
    try:
        global expr
        expr = sy.sympify(new, dict(x=xs))
    except (sy.SympifyError, TypeError, ValueError) as exception:
        dialog.content = str(exception)
        dialog.visible = True
    else:
        update_data()


dialog = Dialog(title="Invalid expression")

slider = Slider(start=1, end=20, value=order, step=1, title="Order:")
slider.on_change('value', on_slider_value_change)

text = TextInput(value=str(expr), title="Expression:")
text.on_change('value', on_text_value_change)

inputs = HBox(children=[slider, text])
layout = VBox(children=[inputs, plot, dialog])
update_data()
document.add_root(layout)
session.show(layout)

if __name__ == "__main__":
    print("\npress ctrl-C to exit")
    session.loop_until_closed()
Ejemplo n.º 16
0
    def create(self):
        manufacturers = sorted(mpg["manufacturer"].unique())
        models = sorted(mpg["model"].unique())
        transmissions = sorted(mpg["trans"].unique())
        drives = sorted(mpg["drv"].unique())
        classes = sorted(mpg["class"].unique())

        manufacturer_select = Select(title="Manufacturer:",
                                     value="All",
                                     options=["All"] + manufacturers)
        manufacturer_select.on_change('value', self.on_manufacturer_change)
        model_select = Select(title="Model:",
                              value="All",
                              options=["All"] + models)
        model_select.on_change('value', self.on_model_change)
        transmission_select = Select(title="Transmission:",
                                     value="All",
                                     options=["All"] + transmissions)
        transmission_select.on_change('value', self.on_transmission_change)
        drive_select = Select(title="Drive:",
                              value="All",
                              options=["All"] + drives)
        drive_select.on_change('value', self.on_drive_change)
        class_select = Select(title="Class:",
                              value="All",
                              options=["All"] + classes)
        class_select.on_change('value', self.on_class_change)

        columns = [
            TableColumn(field="manufacturer",
                        title="Manufacturer",
                        editor=SelectEditor(options=manufacturers),
                        formatter=StringFormatter(font_style="bold")),
            TableColumn(field="model",
                        title="Model",
                        editor=StringEditor(completions=models)),
            TableColumn(field="displ",
                        title="Displacement",
                        editor=NumberEditor(step=0.1),
                        formatter=NumberFormatter(format="0.0")),
            TableColumn(field="year", title="Year", editor=IntEditor()),
            TableColumn(field="cyl", title="Cylinders", editor=IntEditor()),
            TableColumn(field="trans",
                        title="Transmission",
                        editor=SelectEditor(options=transmissions)),
            TableColumn(field="drv",
                        title="Drive",
                        editor=SelectEditor(options=drives)),
            TableColumn(field="class",
                        title="Class",
                        editor=SelectEditor(options=classes)),
            TableColumn(field="cty", title="City MPG", editor=IntEditor()),
            TableColumn(field="hwy", title="Highway MPG", editor=IntEditor()),
        ]
        data_table = DataTable(source=self.source,
                               columns=columns,
                               editable=True)

        plot = Plot(title=None,
                    x_range=DataRange1d(),
                    y_range=DataRange1d(),
                    plot_width=1000,
                    plot_height=300)

        # Set up x & y axis
        plot.add_layout(LinearAxis(), 'below')
        yaxis = LinearAxis()
        plot.add_layout(yaxis, 'left')
        plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

        # Add Glyphs
        cty_glyph = Circle(x="index",
                           y="cty",
                           fill_color="#396285",
                           size=8,
                           fill_alpha=0.5,
                           line_alpha=0.5)
        hwy_glyph = Circle(x="index",
                           y="hwy",
                           fill_color="#CE603D",
                           size=8,
                           fill_alpha=0.5,
                           line_alpha=0.5)
        cty = plot.add_glyph(self.source, cty_glyph)
        hwy = plot.add_glyph(self.source, hwy_glyph)

        # Add the tools
        tooltips = [
            ("Manufacturer", "@manufacturer"),
            ("Model", "@model"),
            ("Displacement", "@displ"),
            ("Year", "@year"),
            ("Cylinders", "@cyl"),
            ("Transmission", "@trans"),
            ("Drive", "@drv"),
            ("Class", "@class"),
        ]
        cty_hover_tool = HoverTool(renderers=[cty],
                                   tooltips=tooltips + [("City MPG", "@cty")])
        hwy_hover_tool = HoverTool(renderers=[hwy],
                                   tooltips=tooltips +
                                   [("Highway MPG", "@hwy")])
        select_tool = BoxSelectTool(renderers=[cty, hwy], dimensions=['width'])
        plot.add_tools(cty_hover_tool, hwy_hover_tool, select_tool)

        controls = VBox(children=[
            manufacturer_select, model_select, transmission_select,
            drive_select, class_select
        ])
        top_panel = HBox(children=[controls, plot])
        layout = VBox(children=[top_panel, data_table])

        return layout
Ejemplo n.º 17
0
    patches_source = ColumnDataSource(
        dict(xs=[[X[i], X[i + 1], X[i + 1], X[i]] for i in range(len(X[:-1]))],
             ys=[[y0, y0, Y[i + 1], Y[i]] for i in range(len(Y[:-1]))],
             color=data.colors[:-1]))
    patches = Patches(xs="xs", ys="ys", fill_color="color", line_color="color")
    plot.add_glyph(patches_source, patches)

    line_source = ColumnDataSource(dict(x=data.dist, y=data.alt))
    line = Line(x='x', y='y', line_color="black", line_width=1)
    plot.add_glyph(line_source, line)

    return plot


data = prep_data(obiszow_mtb_xcm)

trail = trail_map(data)
altitude = altitude_profile(data)

layout = VBox(children=[altitude, trail])

doc = Document()
doc.add_root(layout)

if __name__ == "__main__":
    filename = "trail.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Trail map and altitude profile"))
    print("Wrote %s" % filename)
    view(filename)
Ejemplo n.º 18
0
def templateRateCorrelation(state):
    DEFAULT_X = ['Amount Requested', 'Annual Income', 'Debt To Income Ratio']

    dati = pd.read_csv(DATA + 'accepted_less_col_small_' + state + '.csv', header=0)

    amnt = dati['amnt']
    income = dati['income']
    dti = dati['dti']
    rate = dati['rate'] / 100

    source = ColumnDataSource(
        data={'x': amnt,
              'y': rate,
              'Amount Requested': amnt,
              'Annual Income': income,
              'Debt To Income Ratio': dti,
              'Rate_per_100': rate * 100}
    )

    codex = """
            var data = source.get('data');
            data['x'] = data[cb_obj.get('value')];//
            // var r = data[cb_obj.get('value')];
            // var {var} = data[cb_obj.get('value')];
            // //window.alert( "{var} " + cb_obj.get('value') + {var}  );
            // for (i = 0; i < r.length; i++) {{
            //     {var}[i] = r[i] ;
            //     data['{var}'][i] = r[i];
            // }}
            source.trigger('change');
        """

    callbackx = CustomJS(args=dict(source=source), code=codex)

    TOOLS = "pan,wheel_zoom,reset,hover,save"
    plot = Figure(title=None, height=400, width=600, tools=TOOLS)

    # Make a line and connect to data source
    plot.circle(x="x", y="y", line_color="#0062cc", line_width=6, line_alpha=0.6, source=source)
    plot.yaxis.axis_label = 'Loan Rate'
    plot.yaxis[0].formatter = NumeralTickFormatter(format="0.0%")

    xaxis_select = Select(title="Label X axis:", value="Amount",
                          options=DEFAULT_X, callback=callbackx)

    hover = plot.select_one(HoverTool)
    hover.point_policy = "follow_mouse"
    hover.tooltips = [
        ("Rate", "@Rate_per_100{1.11}%"),
        ("Amount Requested", "@{Amount Requested}{1.11}"),
        ("Annual Income", "@{Annual Income}{1.11}"),
        ("Debt To Income Ratio", "@{Debt To Income Ratio}{1.11}%")
    ]

    # Layout widgets next to the plot
    controls = VBox(xaxis_select)

    layout = HBox(controls, plot, width=800)

    # show(layout)

    script_corr, div_corr = components(layout)

    return script_corr, div_corr