예제 #1
0
def show_roc_curve_bokeh(fpr,
                         tpr,
                         rocAuc,
                         classes,
                         name,
                         path,
                         show_plt=False):
    output_file("roc.html")
    from bokeh.models import Legend, LegendItem
    p = figure(plot_width=400, plot_height=400)

    # add a line renderer
    r = p.multi_line([fpr["micro"], fpr["macro"], [0, 1]],
                     [tpr["micro"], tpr["macro"], [0, 1]],
                     color=["chocolate", "darkslateblue", "black"],
                     alpha=[0.6, 0.6, 0.3],
                     line_width=2)
    legend = Legend(items=[
        LegendItem(label='micro-average ROC curve (area = {0:0.3f})'
                   ''.format(rocAuc["micro"]),
                   renderers=[r],
                   index=0),
        LegendItem(label='macro-average ROC curve (area = {0:0.2f})'
                   ''.format(rocAuc["macro"]),
                   renderers=[r],
                   index=1),
    ])
    p.add_layout(legend)
    p.legend.location = "bottom_right"

    show(p)
예제 #2
0
def make_plot(cnv_name, test_name, data, d_min, d_max):
    plot = figure(title=test_name,
                  plot_width=700,
                  plot_height=500,
                  min_border=0)

    glyph1 = VArea(x="x1",
                   y1="y01",
                   y2="y1",
                   fill_color="LightCoral",
                   fill_alpha=0.6)
    glyph2 = VArea(x="x2",
                   y1="y02",
                   y2="y2",
                   fill_color="LightBlue",
                   fill_alpha=0.6)
    plot.add_glyph(data, glyph1)
    plot.add_glyph(data, glyph2)

    li1 = LegendItem(label='0 (Absent)', renderers=[plot.renderers[0]])
    li2 = LegendItem(label='1 (Present)', renderers=[plot.renderers[1]])
    legend1 = Legend(items=[li1, li2], location='top_right')
    plot.add_layout(legend1)
    plot.legend.title = cnv_name

    return plot
예제 #3
0
def get_map_plot(source, source_elog, source_radius_circle):

    #define maps, options
    map_options = GMapOptions(lat=51.4416, lng=5.4697, map_type="terrain", zoom=12)
    plot = GMapPlot(x_range=Range1d(), y_range=Range1d(), map_options=map_options)

    # use your api key below
    plot.api_key = get_api_key()

    ########################################################################
    # Define glyphs
    ########################################################################

    # triangle glyphs on the map
    triangle_event = Triangle(x="lon", y="lat", size=12, fill_color="red", fill_alpha=0.5, line_color=None, name="events")
    glyph_triangle = plot.add_glyph(source, triangle_event, nonselection_glyph=triangle_event)

    # circle glyphs on the map
    circle_elog = Circle(x="lon_elog", y="lat_elog", size=12, fill_color="color",
    fill_alpha=0.8, line_color=None, name="elog_locations")
    glyph_circle = plot.add_glyph(source_elog, circle_elog, nonselection_glyph=circle_elog, )

    circle_radius = Circle(x="lon_radius", y="lat_radius", radius= "rad_radius", fill_alpha=0.3, line_color='black')
    glyph_circle_radius = plot.add_glyph(source_radius_circle, circle_radius)

    ########################################################################
    # Other misc tools: hovers, taps, etc
    ########################################################################

    # tools to include on the visualization
    plot.add_tools(PanTool(), WheelZoomTool(),
    	    ResetTool(), TapTool())

    # Hover tool for triangles
    triangle_hover = HoverTool(renderers=[glyph_triangle],
                             tooltips=OrderedDict([
                                 ("Location", "@city"),
                                 ("Date", "@dates"),
                                 ("Problem", "@issue")
                             ]))
    plot.add_tools(triangle_hover)

    # Hover tool for circles
    circle_hover = HoverTool(renderers=[glyph_circle],
                             tooltips=OrderedDict([
                                 ("Place", "@place_elog"),
                                 ("Usage", '@value_elog'),
                                 ("Classification", '@classes')
                             ]))
    plot.add_tools(circle_hover)

    # Add legend
    legend = Legend(items=[
        LegendItem(label="elog_locations"   , renderers=[glyph_circle]),
        LegendItem(label="events" , renderers=[glyph_triangle])
    ], orientation="vertical", click_policy="hide")
    plot.add_layout(legend, "center")

    return glyph_circle, plot
예제 #4
0
def test_legend_item_with_field_label_raises_error_if_field_not_in_cds():
    legend_item = LegendItem()
    gr_1 = GlyphRenderer(data_source=ColumnDataSource())
    legend_item.label = field('label')
    legend_item.renderers = [gr_1]
    with mock.patch('bokeh.core.validation.check.log') as mock_logger:
        check_integrity([legend_item])
        assert mock_logger.error.call_count == 1
예제 #5
0
def test__find_legend_item():
    legend = Legend(items=[
        LegendItem(label=dict(value="foo")),
        LegendItem(label=dict(field="bar"))
    ])
    assert bpl._find_legend_item(dict(value="baz"), legend) is None
    assert bpl._find_legend_item(dict(value="foo"), legend) is legend.items[0]
    assert bpl._find_legend_item(dict(field="bar"), legend) is legend.items[1]
예제 #6
0
def test_can_add_multiple_glyph_renderers_to_legend_item() -> None:
    legend_item = LegendItem()
    gr_1 = GlyphRenderer()
    gr_2 = GlyphRenderer()
    legend_item.renderers = [gr_1, gr_2]
    with mock.patch('bokeh.core.validation.check.log') as mock_logger:
        check_integrity([legend_item])
        assert mock_logger.error.call_count == 0
예제 #7
0
def test_can_add_multiple_glyph_renderers_to_legend_item() -> None:
    legend_item = LegendItem()
    gr_1 = GlyphRenderer(data_source=ColumnDataSource())
    gr_2 = GlyphRenderer(data_source=ColumnDataSource())
    legend_item.renderers = [gr_1, gr_2]
    with mock.patch('bokeh.core.validation.check.log') as mock_logger:
        issues = check_integrity([legend_item])
        process_validation_issues(issues)
        assert mock_logger.error.call_count == 0
예제 #8
0
def test_legend_item_with_value_label_and_different_data_sources_does_not_raise_a_validation_error() -> None:
    legend_item = LegendItem()
    gr_1 = GlyphRenderer(data_source=ColumnDataSource())
    gr_2 = GlyphRenderer(data_source=ColumnDataSource())
    legend_item.label = value('label')
    legend_item.renderers = [gr_1, gr_2]
    with mock.patch('bokeh.core.validation.check.log') as mock_logger:
        check_integrity([legend_item])
        assert mock_logger.error.call_count == 0
예제 #9
0
def render_scatter(
    itmdt: Intermediate, plot_width: int, plot_height: int, palette: Sequence[str]
) -> Figure:
    """
    Render scatter plot with a regression line and possible most influencial points
    """

    # pylint: disable=too-many-locals

    df = itmdt["data"]
    xcol, ycol, *maybe_label = df.columns

    tooltips = [(xcol, f"@{{{xcol}}}"), (ycol, f"@{{{ycol}}}")]

    fig = Figure(
        plot_width=plot_width,
        plot_height=plot_height,
        toolbar_location=None,
        title=Title(text="Scatter Plot & Regression Line", align="center"),
        tools=[],
        x_axis_label=xcol,
        y_axis_label=ycol,
    )

    # Scatter
    scatter = fig.scatter(x=df.columns[0], y=df.columns[1], source=df)
    if maybe_label:
        assert len(maybe_label) == 1
        mapper = CategoricalColorMapper(factors=["=", "+", "-"], palette=palette)
        scatter.glyph.fill_color = {"field": maybe_label[0], "transform": mapper}
        scatter.glyph.line_color = {"field": maybe_label[0], "transform": mapper}

    # Regression line
    coeff_a, coeff_b = itmdt["coeffs"]
    line_x = np.asarray([df.iloc[:, 0].min(), df.iloc[:, 0].max()])
    line_y = coeff_a * line_x + coeff_b
    fig.line(x=line_x, y=line_y, line_width=3)
    # Not adding the tooltips before because we only want to apply tooltip to the scatter
    hover = HoverTool(tooltips=tooltips, renderers=[scatter])
    fig.add_tools(hover)

    # Add legends
    if maybe_label:
        nidx = df.index[df[maybe_label[0]] == "-"][0]
        pidx = df.index[df[maybe_label[0]] == "+"][0]

        legend = Legend(
            items=[
                LegendItem(label="Most Influential (-)", renderers=[scatter], index=nidx),
                LegendItem(label="Most Influential (+)", renderers=[scatter], index=pidx),
            ],
            margin=0,
            padding=0,
        )

        fig.add_layout(legend, place="right")
    return fig
예제 #10
0
파일: views.py 프로젝트: emilyngodby/VRRT
    def get(self, request):

        fieldValue = "respirationRate"

        userName = ""
        #Checks if the current uesr has been authed
        if request.user.is_authenticated:
            #Getting the current users username
            userName = request.user.username

        results = databaseUserQuery(fieldValue, userName)

        results = databaseQuerryParser(results,fieldValue)

        print("\t\tRESULTS: " + str(results))

        startValues = results[0]
        endValues = results[1]

        xVals = []

        for i in range(1,len(startValues)+1):
            xVals.append(i)

        #xVals = range(len(startValues))

        source = ColumnDataSource(data=dict(
            x = xVals,
            y1 = startValues,
            y2 = endValues
        ))

        p = figure( sizing_mode = "stretch_width", plot_height = 350)

        r = p.multi_line([xVals,xVals],[startValues,endValues], color=["firebrick", "navy"], alpha=[0.8, 0.3], line_width=4)

        p.background_fill_color = None
        p.border_fill_color = None
        p.title = 'Change in Respiration Rate'

        p.yaxis.axis_label = "RespirationRate(Breaths/m)"
        p.xaxis.axis_label = "Session"

        legend = Legend(items=[
            LegendItem(label="Start Values", renderers=[r],  index=0),
            LegendItem(label="End Values", renderers=[r], index=1),
            ])
        p.add_layout(legend)

        p.legend.location = "top_left"
        p.legend.title_text_font = 'Arial'
        p.legend.title_text_font_size = '20pt'

        script, div = components(p)

        return pageUserAuth(request,'Patient',"patient_progress.html", {'script' : script , 'div': div} )
예제 #11
0
def test_legend_item_with_field_label_and_different_data_sources_raises_a_validation_error(
):
    legend_item = LegendItem()
    gr_1 = GlyphRenderer(data_source=ColumnDataSource(data={'label': [1]}))
    gr_2 = GlyphRenderer(data_source=ColumnDataSource(data={'label': [1]}))
    legend_item.label = field('label')
    legend_item.renderers = [gr_1, gr_2]
    with mock.patch('bokeh.core.validation.check.log') as mock_logger:
        check_integrity([legend_item])
        assert mock_logger.error.call_count == 1
예제 #12
0
def gen_bokeh_plot():
    # retrieve current active symbol and data source
    data_source = DATA_STORE['data_source']
    title_source = DATA_STORE['title_source']

    # calculate mean absolute deviation (MAD)
    title = Title(text='Predicted vs Actual Market Open Price')

    plot = Plot(title=title,
                plot_width=1200,
                plot_height=800,
                h_symmetry=False,
                v_symmetry=False,
                min_border=0,
                toolbar_location='right')

    val_glyph = Line(x='date',
                     y='val_open',
                     line_color='black',
                     line_width=1.5)
    pred_glyph = Line(x='date',
                      y='pred_open',
                      line_color='blue',
                      line_width=1.5,
                      line_dash='dashed')
    plot.add_glyph(data_source, val_glyph)  # renderer 0
    plot.add_glyph(data_source, pred_glyph)  # renderer 1

    text_glyph = Text(x='x', y='y', text='text')
    plot.add_glyph(title_source, text_glyph)

    # Format plot
    li1 = LegendItem(label='actual', renderers=[plot.renderers[0]])
    li2 = LegendItem(label='predicted', renderers=[plot.renderers[1]])
    legend1 = Legend(items=[li1, li2], location='top_right')
    plot.add_layout(legend1)

    xaxis = DatetimeAxis()
    xaxis.formatter = DatetimeTickFormatter(years=['%Y'],
                                            months=['%m/%Y'],
                                            days=['%d/%m/%Y'])
    xaxis.major_label_orientation = np.pi / 4
    plot.add_layout(xaxis, 'below')

    yaxis = LinearAxis()
    plot.add_layout(yaxis, 'left')

    return plot
예제 #13
0
def display_season_overview(src, seasonNum, yrange, xrange):    # creating and displaying visualizations
    figure_season_overview = figure(title="Season Overview : "+str(seasonNum), tools="hover, save",\
               y_range=yrange, x_range=list(xrange), plot_width=1200, plot_height=500)
    
    figure_season_overview.xaxis.major_label_orientation = 45    # Configuring
    figure_season_overview.yaxis.axis_label = 'Stadium Cities'   # figure
    figure_season_overview.xaxis.axis_label = 'Dates'            # settings
    
    rect = Rect(x="dates", y="cities", width=0.8, height=0.8, fill_alpha=0.8, fill_color="type_color")
    rect_render = figure_season_overview.add_glyph(src, rect)
    
    legend = Legend(items=[ LegendItem(label=field("label"), renderers=[rect_render]) ])
    figure_season_overview.add_layout(legend, 'left')

    figure_season_overview.legend.background_fill_color = "grey"
    figure_season_overview.legend.background_fill_alpha = 0.1
    figure_season_overview.legend.border_line_color = "black"
    
    figure_season_overview.select_one(HoverTool).tooltips = [
                ("Date", "@dates"),
                ("Team1", "@team1"),                             # Configuring
                ("Team2", "@team2"),                             # Hover
                ("Venue", "@venues"),                            # Tool
                ("City", "@cities"),
                ("Winner", "@winners"),
                ("Man of the match","@player_of_match")
            ]
    return figure_season_overview                                                                 # displaying generated visualization
예제 #14
0
def pvmodule_detail(request, pvmodule_id):
    pvmod = get_object_or_404(PVModule, pk=pvmodule_id)
    fieldnames = PVModule._meta.get_fields()
    pvmod_dict = {k.name: getattr(pvmod, k.name) for k in fieldnames}
    for k in ['IXO', 'IXXO', 'C4', 'C5', 'C6', 'C7']:
        if pvmod_dict[k] is None:
            pvmod_dict[k] = 0.
    celltemps = np.linspace(0, 100, 5)
    effirrad, celltemp = np.meshgrid(np.linspace(0.1, 1, 10), celltemps)
    results = sapm(effirrad, celltemp, pvmod_dict)
    eff = results['p_mp'] / effirrad / pvmod.Area * 100 / 1000
    fig = figure(
        x_axis_label='effective irradiance, Ee [suns]',
        y_axis_label='efficiency [%]',
        title=pvmod.Name,
        plot_width=800, plot_height=600, sizing_mode='scale_width'
    )
    r = fig.multi_line(
        effirrad.tolist(), eff.tolist(), color=cmap, line_width=4)
    legend = Legend(items=[
        LegendItem(label='{:d} [C]'.format(int(ct)), renderers=[r], index=n)
        for n, ct in enumerate(celltemps)])
    fig.add_layout(legend)
    plot_script, plot_div = components(fig)
    return render(
        request, 'pvmodule_detail.html', {
            'path': request.path, 'pvmod': pvmod, 'plot_script': plot_script,
            'plot_div': plot_div, 'pvmod_dict': pvmod_dict})
예제 #15
0
 def test_label_already_exists(self) -> None:
     legend = Legend(items=[LegendItem(label=dict(value="foo"))])
     renderer = GlyphRenderer()
     bpl._handle_legend_label("foo", legend, renderer)
     assert len(legend.items) == 1
     assert legend.items[0].label == dict(value="foo")
     assert legend.items[0].renderers == [renderer]
예제 #16
0
    def __populate_scrubber(cls, scrubber, scrubberdf, scrubbersource,
                            columnmap):
        categorycol = columnmap['scrubber_category']
        resultcol = columnmap['result']
        colorcol = columnmap['scrubber_color']
        timecol = columnmap['timeline_start_ts']

        results = scrubberdf[resultcol].unique()
        scrubber.y_range.update(factors=results)

        categories = scrubberdf[categorycol].unique()
        scrubber_legends_items = []
        for category in categories:
            view = CDSView(
                source=scrubbersource,
                filters=[GroupFilter(column_name=categorycol, group=category)])
            renderer = scrubber.circle(x=timecol,
                                       y=resultcol,
                                       size=12,
                                       source=scrubbersource,
                                       view=view,
                                       color=colorcol)
            scrubber_legends_items.append(
                LegendItem(label=category, renderers=[renderer]))

        legend = Legend(items=scrubber_legends_items)
        legend.click_policy = 'hide'
        scrubber.add_layout(legend, 'left')
        return scrubber
예제 #17
0
def ave_azav_fig(ave_azav, peak_bin, bin_start, bin_end):
    """Generate the azav fig for html file"""
    x_vals = np.arange(len(ave_azav))
    fig = figure(
        title=
        f'Average Azimuthal Binned Array: Center - {peak_bin}, min/max - {bin_start}/{bin_end}',
        x_axis_label='Bins',
        y_axis_label='Intensity',
    )

    peak_line = Span(location=peak_bin,
                     dimension='height',
                     line_color='green',
                     line_width=2)
    lower_line = Span(location=bin_start,
                      dimension='height',
                      line_color='black')
    upper_line = Span(location=bin_end, dimension='height', line_color='black')
    ave_azav_curve = fig.scatter(x_vals, ave_azav)
    fig.renderers.extend([peak_line, lower_line, upper_line])

    azav_legend = Legend(items=[
        LegendItem(label='Azimuthal Average', renderers=[ave_azav_curve])
    ])
    fig.add_layout(azav_legend)

    return fig
예제 #18
0
def test_legend_powered_by_source(output_file_url, selenium, screenshot):
    plot = Plot(height=HEIGHT,
                width=WIDTH,
                x_range=Range1d(0, 4),
                y_range=Range1d(0, 4),
                toolbar_location=None)
    source = ColumnDataSource(
        dict(
            x=[1, 2, 3],
            y=[1, 2, 3],
            color=['red', 'green', 'blue'],
            label=['Color Red', 'Color Green', 'Color Blue'],
        ))
    circle = Circle(x='x', y='y', fill_color='color', size=20)
    circle_renderer = plot.add_glyph(source, circle)
    plot.add_layout(
        Legend(items=[
            LegendItem(label=field('label'), renderers=[circle_renderer])
        ]))

    # Save the plot and start the test
    save(plot)
    selenium.get(output_file_url)
    assert has_no_console_errors(selenium)

    # Take screenshot
    assert screenshot.is_valid()
예제 #19
0
def test_LegendItem() -> None:
    item = LegendItem()
    assert item.index is None
    assert item.label is None
    assert item.name is None
    assert item.renderers == []
    assert item.visible is True
예제 #20
0
    def make_pie_plot(src):

        p = figure(plot_width=300,
                   plot_height=800,
                   title="Pie Chart",
                   toolbar_location=None,
                   tools="hover",
                   tooltips="@word_types: @counts",
                   x_range=(-0.5, 1.0))

        r = p.wedge(
            x=0,
            y=1,
            radius=0.4,
            start_angle=cumsum('angle', include_zero=True),
            end_angle=cumsum('angle'),
            line_color="white",
            fill_color='color',
            # legend='word_types', source=src)
            source=src)

        legend = Legend(
            items=[LegendItem(label=dict(field="word_types"), renderers=[r])],
            location=(0, 30))
        p.add_layout(legend, 'below')
        p.axis.axis_label = None
        p.axis.visible = False
        p.grid.grid_line_color = None

        return p
예제 #21
0
    def make_plot_diff(src, country_to_plot):

        p = figure(
            title=f"{country_to_plot}: Number of Cases Per Day Increase",
            #y_axis_type="log",
            x_axis_type='datetime',
            plot_height=600,
            plot_width=950)
        p.title.text_font = "helvetica"
        p.title.text_font_size = "20px"
        p.xgrid.grid_line_color = None
        p.ygrid.grid_line_color = None

        palette = Category20[7]  # brewer['PuBu'][9]#gray(21)
        colors = [palette[0], palette[6], palette[4]]
        cases = ['Confirmed', 'Deaths', 'Recovered']
        diffs = ['ConfirmedDiff', 'DeathsDiff', 'RecoveredDiff']
        items = []
        for i, case in enumerate(diffs):
            c = p.line('Date',
                       case,
                       line_color=colors[i],
                       line_width=2.5,
                       source=src)
            point = p.circle('Date',
                             case,
                             line_color=colors[i],
                             fill_color=colors[i],
                             fill_alpha=0,
                             size=7,
                             source=src)
            hover = HoverTool(
                tooltips=[("Date", "@Date{%F}"), (f"{case}", "$y")],
                formatters={
                    '@Date':
                    'datetime'  # use 'datetime' formatter for '@date' field
                },
                renderers=[c])
            items.append(LegendItem(label=cases[i], renderers=[point, c]))
            p.add_tools(hover)

        legend = Legend(items=items,
                        location='top_left')  #, location=(0, -30))
        p.add_layout(legend, 'center')

        p.legend.location = "top_left"
        p.legend.click_policy = "hide"
        p.legend.background_fill_alpha = 0
        p.legend.border_line_alpha = 0
        p.legend.glyph_height = 20
        p.legend.glyph_width = 20
        p.legend.label_text_font_size = '20pt'

        p.xaxis.ticker.desired_num_ticks = 25

        p.xaxis.axis_label = 'Date'
        #p.yaxis.axis_label = 'Counts/100k inhabitants'
        p.yaxis.axis_label = 'Per day increase'

        return p
예제 #22
0
 def _update_legends(self, space, attr, old, new):
     if len(self._plot[space].legend.items) == 3:
         self._plot[space].legend.items.pop()
     r = self._plot[space].select(name="sel")
     pvalue = self._pvalue_rec[space].data["pv"]
     if len(r) and len(pvalue):
         self._plot[space].legend.items.append(LegendItem(label="p-value = "+format(pvalue[0],'.4f'), \
                                                             renderers=[r[0]]))
예제 #23
0
def compare_plot(data):
    """
    functions for creating the WAIC compare plot function. Creates data for WAIC here using the 
    dictionary of models provided. Plot doesn't need to be dynamically redrawn with interactive 
    functions so latency is not really an issue. Which is why its easier just to create the WAIC
    data here. Plot only redrawn each time a new model is added.
    """
    model_data = {}
    for key, value in data.items():
        model_data[key] = value.model_arviz_data
    comp = az.compare(
            model_data, 
            ic='waic',
            scale='log',
            )
    comp.replace([np.inf, -np.inf], np.nan)
    if comp.isnull().values.any():
        # if null values present then - in the cases ive seen - it means the model is using data
        # with missing values. Therefore notify the user that this feature is not available.
        return pn.widgets.StaticText(name='', value='Data contains missing values so can\'t compute WAIC')
    
    elif comp.shape[0] < 2:
        # for some reason this plot creates an error tha will stop the whole app from loading 
        # if only one model is plotted. Therefore notify the user that a second configuration 
        # is required before this feature is enabled.
        return pn.widgets.StaticText(name='', value='Add another configuration to compare models')

    else:
        kwg = dict(height=450, width=650,toolbar_location='right')
        plot = az.plot_compare(
                comp,
                backend='bokeh',
                show=False,
                backend_kwargs=kwg,
                order_by_rank=True,
                )
        # plot does not generate a legend automatically so create one manually here by capturing the
        # plot features and giving them labels
        li1 = LegendItem(label='WAIC', renderers=[plot.renderers[2]])
        li2 = LegendItem(label='Stadard Error', renderers=[plot.renderers[3]])
        li3 = LegendItem(label='In-Sample Deviance', renderers=[plot.renderers[4]])
        legend = Legend(items=[li1, li2, li3])
        legend.location = (10,-10)
        plot.add_layout(legend, place='right')
        plot.width = 800
        return plot
예제 #24
0
def when_changing_county_2(attr, old, new):
  state_name = select_state_2.value
  county_name = select_county_2.value

  set_legend1_2(legend1, county_name, state_name, q4, q5)
  set_legend1_2(legend1_log, county_name, state_name, q4_log, q5_log)

  set_legend2_2(legend2, county_name, state_name, s2, s3)
  set_legend2_2(legend2_log, county_name, state_name, s2_log, s3_log)

  legend4.items[0] = LegendItem(label=county_name + " Cases/" + state_name + " Cases", renderers=[t2])
  legend4.items[1] = LegendItem(label=county_name + " Deaths/" + state_name + " Deaths", renderers=[t3])

  state = us_counties.groupby("state").get_group(state_name)
  res = state.groupby("county")
  county = res.get_group(county_name)

  source1.data = county
예제 #25
0
 def test_field_string(self) -> None:
     legend = Legend(items=[LegendItem(label=dict(field="foo"))])
     renderer = GlyphRenderer(data_source=ColumnDataSource(data=dict(foo=[], bar=[])))
     bpl._handle_legend_deprecated("foo", legend, renderer)
     assert len(legend.items) == 1
     assert all("field" in item.label for item in legend.items)
     bpl._handle_legend_deprecated("bar", legend, renderer)
     assert len(legend.items) == 2
     assert all("field" in item.label for item in legend.items)
예제 #26
0
def get_detailed_loss(loss, title):
    loss, rec_l, kld_l = loss
    fig = figure(title=title)
    indices = list(range(1, len(loss) + 1))
    x = [indices, indices, indices]
    y = [loss, rec_l, kld_l]
    colors = ["black", "red", "green"]

    r = fig.multi_line(x, y, color=colors)
    legends = [LegendItem(label="Rec + KLD", renderers=[r], index=0)]
    legends.append(LegendItem(label="Reconstr", renderers=[r], index=1))
    legends.append(LegendItem(label="KLD", renderers=[r], index=2))

    legend = Legend(items=legends)
    fig.add_layout(legend)
    fig.xaxis.axis_label = 'Epoch'
    fig.yaxis.axis_label = 'Loss'
    return fig
예제 #27
0
 def test_value_dict(self) -> None:
     legend = Legend(items=[LegendItem(label=dict(value="foo"))])
     renderer = GlyphRenderer(data_source=ColumnDataSource())
     bpl._handle_legend_deprecated(dict(value="foo"), legend, renderer)
     assert len(legend.items) == 1
     assert all("value" in item.label for item in legend.items)
     bpl._handle_legend_deprecated(dict(value="bar"), legend, renderer)
     assert len(legend.items) == 2
     assert all("value" in item.label for item in legend.items)
예제 #28
0
 def test_label_not_already_exists(self) -> None:
     legend = Legend(items=[LegendItem(label=dict(field="foo"))])
     renderer = GlyphRenderer()
     bpl._handle_legend_field("bar", legend, renderer)
     assert len(legend.items) == 2
     assert legend.items[0].label == dict(field="foo")
     assert legend.items[0].renderers == []
     assert legend.items[1].label == dict(field="bar")
     assert legend.items[1].renderers == [renderer]
예제 #29
0
def plot_cost_surface(sample_size=None, fig_kwargs=None):
    """
    using a, b, c as parameters of quadratic
    and m, k as slope, intercept of line
    """
    p = _init_surface_plot(sample_size, fig_kwargs)
    source, mapper = _compute_cost_surface(sample_size)
    p.image("log",
            x="x",
            y="y",
            dw="dw",
            dh="dh",
            color_mapper=mapper,
            source=source,
            name="img",
            level="image")

    items = []
    r = p.plus([b_star], [m_star],
               line_color="#000000",
               line_width=0.8,
               fill_color="#ffffff",
               size=10)
    items.append(LegendItem(renderers=[r], label="True best parameters"))
    if sample_size is not None:
        _x = x[:sample_size]
        _y = y[:sample_size]
        m_hat = ((_y.sum() * _x.sum() / sample_size - (_y * _x).sum()) /
                 ((_x.sum())**2 / sample_size - (_x**2).sum()))
        k_hat = _y.sum() / sample_size - m_hat * _x.sum() / sample_size
        r = p.plus([k_hat], [m_hat],
                   line_color="#000000",
                   line_width=1.5,
                   fill_color="#000000",
                   size=10)
        items.append(LegendItem(renderers=[r], label="Best fit on sample"))

    p.add_layout(Legend(items=items), "right")
    p.add_tools(
        HoverTool(renderers=p.select("img"),
                  tooltips=[("Slope", "$y"), ("Intercept", "$x"),
                            ("Expected Error", "@img")]))
    return p
예제 #30
0
def when_changing_county(attr, old, new):
  state_name = select_state.value
  county_name = select_county.value

  set_legend1_1(legend1, county_name, state_name, q2, q3)
  set_legend1_1(legend1_log, county_name, state_name, q2_log, q3_log)

  set_legend2_1(legend2, county_name, state_name, s0, s1)
  set_legend2_1(legend2_log, county_name, state_name, s0_log, s1_log)

  legend3.items[0] = LegendItem(label=county_name + " Cases/" + state_name + " Cases", renderers=[t0])
  legend3.items[1] = LegendItem(label=county_name + " Deaths/" + state_name + " Deaths", renderers=[t1])

  state = us_counties.groupby("state").get_group(state_name)
  res = state.groupby("county")
  county = res.get_group(county_name)

  source.data = county
  source2.data = res.get_group(" All Counties")