Beispiel #1
0
    def build_renderers(self):
        """Yields all renderers that make up the BoxGlyph."""

        self.calc_quartiles()
        outlier_values = self.values[((self.values < self.w0) |
                                      (self.values > self.w1))]

        self.whisker_glyph = GlyphRenderer(
            glyph=Segment(x0='x0s',
                          y0='y0s',
                          x1='x1s',
                          y1='y1s',
                          line_width=self.whisker_line_width,
                          line_color=self.whisker_color))

        if len(outlier_values) > 0 and self.outliers:
            self.outliers = PointGlyph(label=self.label,
                                       y=outlier_values,
                                       x=[self.get_dodge_label()] *
                                       len(outlier_values),
                                       line_color=self.outlier_line_color,
                                       fill_color=self.outlier_fill_color,
                                       size=self.outlier_size,
                                       marker=self.marker)

        for comp_glyph in self.composite_glyphs:
            for renderer in comp_glyph.renderers:
                yield renderer

        yield self.whisker_glyph
Beispiel #2
0
def test_Segment():
    glyph = Segment()
    assert glyph.x0 is None
    assert glyph.y0 is None
    assert glyph.x1 is None
    assert glyph.y1 is None
    check_line_properties(glyph)
    check_properties_existence(glyph, ["x0", "y0", "x1", "y1"], LINE, GLYPH)
Beispiel #3
0
def test_Segment():
    glyph = Segment()
    assert glyph.x0 is None
    assert glyph.y0 is None
    assert glyph.x1 is None
    assert glyph.y1 is None
    yield check_line, glyph
    yield (check_props, glyph, ["x0", "y0", "x1", "y1"], LINE)
Beispiel #4
0
def test_Segment() -> None:
    glyph = Segment()
    assert glyph.x0 == field("x0")
    assert glyph.y0 == field("y0")
    assert glyph.x1 == field("x1")
    assert glyph.y1 == field("y1")
    check_line_properties(glyph)
    check_properties_existence(glyph, ["x0", "y0", "x1", "y1"], LINE, GLYPH)
Beispiel #5
0
def test_Segment():
    glyph = Segment()
    assert glyph.x0 == "x0"
    assert glyph.y0 == "y0"
    assert glyph.x1 == "x1"
    assert glyph.y1 == "y1"
    yield check_line, glyph
    yield (check_props, glyph, ["x0", "y0", "x1", "y1"], LINE)
 def bokeh_glyph(self):
     return Segment(
         x0='x0',
         x1='x1',
         y0='y0',
         y1='y1',
         line_alpha=0,
     )
Beispiel #7
0
def add_trips_to_plot(p, trips):
    """Add trip glyphs to plot `p`."""
    data_source = ColumnDataSource(
        pd.concat(
            [
                trips,
                pd.DataFrame({
                    "marker_size": 8 * trips["n_passengers"],
                    "marker_angle": marker_angle(trips),
                }),
            ],
            axis=1,
        ))
    p.add_glyph(
        data_source,
        Segment(
            x0="pick_lon",
            y0="pick_lat",
            x1="drop_lon",
            y1="drop_lat",
            line_color="black",
            line_width=1,
        ),
    )
    p.add_glyph(
        data_source,
        Circle(
            x="pick_lon",
            y="pick_lat",
            size="marker_size",
            fill_color="blue",
            fill_alpha=0.6,
        ),
    )
    p.add_glyph(
        data_source,
        Triangle(
            x="drop_lon",
            y="drop_lat",
            size="marker_size",
            angle="marker_angle",
            fill_color="red",
            fill_alpha=0.6,
        ),
    )
Beispiel #8
0
    def build_renderers(self):
        if self.stem:
            yield GlyphRenderer(glyph=Segment(
                x0='x', y0=0, x1='x', y1='height',
                line_width=self.stem_line_width,
                line_color=self.stem_color,
                line_alpha='fill_alpha')
            )

        glyph_type = self.get_glyph()
        glyph = glyph_type(x='x', y='height',
                           line_color=self.line_color,
                           fill_color=self.color,
                           size=self.size,
                           fill_alpha='fill_alpha',
                           line_alpha='line_alpha'
                           )
        yield GlyphRenderer(glyph=glyph)
Beispiel #9
0
    def segment(self,
                source,
                x0='segx0',
                x1='segx1',
                y0='segy0',
                y1='segy1',
                line_width=2,
                line_color='#1e90ff'):
        seg = Segment(x0=x0,
                      x1=x1,
                      y0=y0,
                      y1=y1,
                      line_width=line_width,
                      line_color=line_color)

        self.plot.add_glyph(source, seg)

        self.plot.yaxis.ticker = FixedTicker(ticks=[0, 1])
        self.plot.yaxis.major_label_overrides = {'0': 'bad', '1': 'good'}
        return self
Beispiel #10
0
def plot_choiceset_links(linkfile_df,cost="sim_cost",paths=False):
    
    linkfile_df["color"]= map(assignColorByMode, linkfile_df["mode"])
    if paths:
        linkfile_df["annotation"]= map(createLinkPathAnnotation, linkfile_df["mode"], linkfile_df[cost], linkfile_df["route_id"], linkfile_df["trip_id"], linkfile_df["probability"])
    else:
        linkfile_df["annotation"]=map(createLinkAnnotation, linkfile_df["mode"], linkfile_df[cost], linkfile_df["route_id"], linkfile_df["trip_id"])
    

    linkfile_df["yloc"]= map(yloc, linkfile_df["pathnum"],linkfile_df["linknum"])
    pathnums = list(set(list(linkfile_df["pathnum"])))
    plots = {}
    for p in pathnums:
        data_df = linkfile_df[linkfile_df["pathnum"]==p]
        linksource = ColumnDataSource(data_df)

        xdr2 = DataRange1d()
        ydr2 = DataRange1d()

        plots[p] = Plot(
            title="Path Number: %d    Probability: %4.2f Percent" % (p,100*data_df["probability"].max()), x_range=xdr2, y_range=ydr2, plot_width=800, plot_height=150,
            h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None)

        glyph = Segment(y0="yloc", x0="new_A_time", y1="yloc", x1="new_B_time", line_color="color", line_width=cost)
        plots[p].add_glyph(linksource, glyph)

        choicexaxis = DatetimeAxis()
        plots[p].add_layout(choicexaxis, 'below')

        xaxis = DatetimeAxis()
        yaxis = LinearAxis()

        plots[p].add_layout(Grid(dimension=0, ticker=xaxis.ticker))
        plots[p].add_layout(Grid(dimension=1, ticker=yaxis.ticker))

        choice_labels = LabelSet(x="new_A_time", y="yloc", text="annotation", y_offset=-5,x_offset=10,
                          text_font_size="8pt", text_color="#555555",
                          source=linksource, text_align='left')
        plots[p].add_layout(choice_labels)

    return plots.values()
Beispiel #11
0
def plot_choice_links(linkfile_df,cost="sim_cost",paths=False):
    
    linkfile_df["color"]= map(assignColorByMode, linkfile_df["mode"])
    if paths:
        linkfile_df["annotation"]= map(createLinkPathAnnotation, linkfile_df["mode"], linkfile_df[cost], linkfile_df["route_id"], linkfile_df["trip_id"], linkfile_df["probability"])
    else:
        linkfile_df["annotation"]=map(createLinkAnnotation, linkfile_df["mode"], linkfile_df[cost], linkfile_df["route_id"], linkfile_df["trip_id"])
    

    linkfile_df["yloc"]= map(yloc, linkfile_df["pathnum"],linkfile_df["linknum"])

    linksource = ColumnDataSource(linkfile_df)
    #linkfile_df

    xdr2 = DataRange1d()
    ydr2 = DataRange1d()

    choiceplot = Plot(
        title=None, x_range=xdr2, y_range=ydr2, plot_width=800, plot_height=300,
        h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None)

    glyph = Segment(y0="yloc", x0="new_A_time", y1="yloc", x1="new_B_time", line_color="color", line_width=cost)
    choiceplot.add_glyph(linksource, glyph)

    choicexaxis = DatetimeAxis()
    choiceplot.add_layout(choicexaxis, 'below')

    xaxis = DatetimeAxis()
    yaxis = LinearAxis()

    choiceplot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
    choiceplot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

    choice_labels = LabelSet(x="new_A_time", y="yloc", text="annotation", y_offset=-5,x_offset=10,
                      text_font_size="8pt", text_color="#555555",
                      source=linksource, text_align='left')
    choiceplot.add_layout(choice_labels)

    return choiceplot
    def update_plot(self):

        today = Timestamp.today().strftime('%Y-%m-%d')
        today_date = to_datetime(today)

        df = self.counts_data
        weights = self.similarities_data.xs(self.school, level='school_name', axis=1)
        df_all = df[df['school_name'].eq(self.school)]
        present_academic_year = df['academic_year'].unique()[0]

        tooltips = '''
        <div style="font-size: 12px;">
        <span style="font-weight: bold;">@school_name</span> (@school_type, @school_age years old)<br>
        Grade @grade enrollment, as of @reference_date_string<br>
        <br>
        <span style="font-weight: bold;">Attrition</span>: @exit_count_present_cumm (@exit_percent_present_cumm{'0.0%'} change from October 1)<br>
        <span style="font-weight: bold;">Backfill</span>: @enter_count_present_cumm (@enter_percent_present_cumm{'0.0%'} change from October 1)<br>
        <span style="font-weight: bold;">Current total enrollment</span>: @total_enrollment
        </div>
        '''

        ticker_ref = DataFrame({'month': date_range('2014-10-01', '2015-06-01', freq='MS')})
        ticker_ref['marker'] = ticker_ref['month']
        ticker_ref['month'] = ticker_ref['month'].apply(lambda x: x.strftime('%B'))
        ticker_ref = ticker_ref.set_index('marker')['month'].to_dict()

        x_range1d = Range1d(-0.05, 290.0)
        y_index = max(
            -df_all['exit_percent_present_cumm'].min(),
            df_all['enter_percent_present_cumm'].max(),
            -df_all['exit_percent_past_cumm'].min(),
            df_all['enter_percent_past_cumm'].max()
        )
        y_range1d = Range1d(-y_index - 0.005, y_index + 0.005)
        plots = []
        focus_cols = ['enter_percent_present_cumm', 'exit_percent_present_cumm']
        unique_grades = sorted(df_all['grade'].unique().astype('int'))
        for grade in unique_grades:
            grade_weight = weights[grade]
            benchmark_df = DataFrame(columns=focus_cols)
            df_copy = df[df['academic_year'].eq(present_academic_year)].copy().set_index(['school_name', 'grade'])

            for rid, label in sorted(ticker_ref.items(), reverse=True):
                df_copy = df_copy[df_copy['reference_date'].le(rid)]
                df_ave = df_copy.groupby(level=['school_name', 'grade'])[focus_cols].tail(1).\
                    mul(grade_weight, axis=0).sum() / grade_weight.sum()
                df_ave.name = label
                benchmark_df = benchmark_df.append(df_ave)
            benchmark_df = benchmark_df.reset_index()
            benchmark_df['reference_date'] = benchmark_df['index'].map({y: x for x, y in ticker_ref.items()})
            benchmark_df['reference_id'] = benchmark_df['reference_date'].apply(lambda x: x.toordinal()) - \
                df_all['reference_date'].min().toordinal()

            source_df = df_all[df_all['grade'].eq(grade)]
            source_df_rev = source_df.sort_values('reference_id', ascending=False)
            source_df_trunc = source_df.loc[source_df['reference_date'].le(today_date), :]
            source = ColumnDataSource(source_df)
            source_trunc = ColumnDataSource(source_df_trunc)
            patch_source = ColumnDataSource(dict(
                x_past=source_df['reference_id'].tolist() + source_df_rev['reference_id'].tolist(),
                y_past=source_df['enter_percent_past_cumm'].tolist() + source_df_rev['exit_percent_past_cumm'].tolist()
            ))

            plot1 = Plot(
                x_range=x_range1d,
                y_range=y_range1d,
                min_border_bottom=5,
                min_border_top=10,
                min_border_right=10,
                plot_width=700,
                plot_height=150,
                title=None,
                title_text_font_size='0pt',
                title_text_color='grey',
                outline_line_alpha=0.0)

            plot1.add_layout(
                LinearAxis(
                    axis_label='Grade ' + str(grade), axis_label_text_font_size='9pt', minor_tick_line_alpha=0.0,
                    axis_label_text_color='grey',
                    axis_line_alpha=0.1, major_tick_line_alpha=0.1, major_label_text_color='grey',
                    major_label_text_font_size='7pt', formatter=NumeralTickFormatter(format='0%')
                ), 'left')

            patch = Patch(x='x_past', y='y_past', fill_color='#AFAFAD', fill_alpha=0.25, line_alpha=0.0)
            plot1.add_glyph(patch_source, patch)

            line1 = Line(
                x='reference_id', y='enter_percent_present_cumm', line_width=2, line_color='#f7910b', line_alpha=1.0)
            plot1.add_glyph(source_trunc, line1)

            line2 = Line(
                x='reference_id', y='exit_percent_present_cumm', line_width=2, line_color='#f7910b', line_alpha=1.0)
            plot1.add_glyph(source_trunc, line2)

            line_h = Line(x='reference_id', y=0, line_width=1, line_color='black', line_alpha=0.1)
            line_renderer = GlyphRenderer(data_source=source, glyph=line_h, name='line')
            plot1.add_glyph(source, line_h)

            for ind, series in benchmark_df.iterrows():
                x = series['reference_id']
                y_enter = series['enter_percent_present_cumm']
                y_exit = series['exit_percent_present_cumm']
                label = series['index']

                line = Segment(x0=x, x1=x, y0=-y_index, y1=y_index, line_width=1, line_color='#165788', line_alpha=0.1)
                plot1.add_glyph(line)

                linec1 = Segment(
                    x0=x - 3, x1=x + 3, y0=y_enter, y1=y_enter, line_width=1, line_color='#ed2939', line_alpha=1.0)
                plot1.add_glyph(linec1)

                linec2 = Segment(
                    x0=x - 3, x1=x + 3, y0=y_exit, y1=y_exit, line_width=1, line_color='#ed2939', line_alpha=1.0)
                plot1.add_glyph(linec2)

                text = Text(x=x+3, y=-y_index, text=[label], text_font_size='8pt', text_color='grey', text_alpha=0.5)
                plot1.add_glyph(text)

            hover_tool = HoverTool(
                plot=plot1, renderers=[line_renderer], tooltips=tooltips, always_active=False, mode='vline',
                point_policy='follow_mouse', line_policy='prev')
            crosshair_tool = CrosshairTool(plot=plot1, dimensions=['height'])
            zoom_tool = BoxZoomTool(plot=plot1, dimensions=['width'])
            reset_tool = ResetTool(plot=plot1)
            save_tool = PreviewSaveTool(plot=plot1)
            pan_tool = PanTool(plot=plot1, dimensions=['width'])
            help_tool = HelpTool(plot=plot1, help_tooltip='App help page', redirect='http://data.successacademies.org/blog/')
            plot1.tools.extend([hover_tool, zoom_tool, pan_tool, reset_tool, save_tool, help_tool, crosshair_tool])
            plot1.renderers.extend([line_renderer])
            plots.append([plot1])

        self.plot.children = plots
Beispiel #13
0
def radialplot(tree, node_color='node_color', node_size='node_size',
               node_alpha='node_alpha', edge_color='edge_color',
               edge_alpha='edge_alpha', edge_width='edge_width',
               hover_var='hover_var', figsize=(500, 500), **kwargs):
    """ Plots unrooted radial tree.

    Parameters
    ----------
    tree : instance of skbio.TreeNode
       Input tree for plotting.
    node_color : str
       Name of variable in `tree` to color nodes.
    node_size : str
       Name of variable in `tree` that specifies the radius of nodes.
    node_alpha : str
       Name of variable in `tree` to specify node transparency.
    edge_color : str
       Name of variable in `tree` to color edges.
    edge_alpha : str
       Name of variable in `tree` to specify edge transparency.
    edge_width : str
       Name of variable in `tree` to specify edge width.
    hover_var : str
       Name of variable in `tree` to display in the hover menu.
    figsize : tuple, int
       Size of resulting figure.  default: (500, 500)
    **kwargs: dict
       Plotting options to pass into bokeh.models.Plot

    Returns
    -------
    bokeh.models.Plot
       Interactive plotting instance.


    Notes
    -----
    This assumes that the tree is strictly bifurcating.

    See also
    --------
    bifurcate
    """
    warnings.warn("This visualization are deprecated.", DeprecationWarning)
    # This entire function was motivated by
    # http://chuckpr.github.io/blog/trees2.html
    t = UnrootedDendrogram.from_tree(tree.copy())

    nodes = t.coords(figsize[0], figsize[1])

    # fill in all of the node attributes
    def _retreive(tree, x, default):
        return pd.Series({n.name: getattr(n, x, default)
                          for n in tree.levelorder()})

    # default node color to light grey
    nodes[node_color] = _retreive(t, node_color, default='#D3D3D3')
    nodes[node_size] = _retreive(t, node_size, default=1)
    nodes[node_alpha] = _retreive(t, node_alpha, default=1)
    nodes[hover_var] = _retreive(t, hover_var, default=None)

    edges = nodes[['child0', 'child1']]
    edges = edges.dropna(subset=['child0', 'child1'])
    edges = edges.unstack()
    edges = pd.DataFrame({'src_node': edges.index.get_level_values(1),
                          'dest_node': edges.values})
    edges['x0'] = [nodes.loc[n].x for n in edges.src_node]
    edges['x1'] = [nodes.loc[n].x for n in edges.dest_node]
    edges['y0'] = [nodes.loc[n].y for n in edges.src_node]
    edges['y1'] = [nodes.loc[n].y for n in edges.dest_node]
    ns = [n.name for n in t.levelorder(include_self=True)]
    attrs = pd.DataFrame(index=ns)

    # default edge color to black
    attrs[edge_color] = _retreive(t, edge_color, default='#000000')
    attrs[edge_width] = _retreive(t, edge_width, default=1)
    attrs[edge_alpha] = _retreive(t, edge_alpha, default=1)

    edges = pd.merge(edges, attrs, left_on='dest_node',
                     right_index=True, how='outer')
    edges = edges.dropna(subset=['src_node'])

    node_glyph = Circle(x="x", y="y",
                        radius=node_size,
                        fill_color=node_color,
                        fill_alpha=node_alpha)

    edge_glyph = Segment(x0="x0", y0="y0",
                         x1="x1", y1="y1",
                         line_color=edge_color,
                         line_alpha=edge_alpha,
                         line_width=edge_width)

    def df2ds(df):
        return ColumnDataSource(ColumnDataSource.from_df(df))

    ydr = DataRange1d(range_padding=0.05)
    xdr = DataRange1d(range_padding=0.05)

    plot = Plot(x_range=xdr, y_range=ydr, **kwargs)
    plot.add_glyph(df2ds(edges), edge_glyph)
    ns = plot.add_glyph(df2ds(nodes), node_glyph)

    tooltip = [
        ("Feature ID", "@index")
    ]
    if hover_var is not None:
        tooltip += [(hover_var, "@" + hover_var)]

    hover = HoverTool(renderers=[ns], tooltips=tooltip)
    plot.add_tools(hover, BoxZoomTool(), ResetTool(),
                   WheelZoomTool(), SaveTool(), PanTool())

    return plot
Beispiel #14
0
normalized_values = [(x * 1.0) / y for x, y in zip(values, max_values)]
cm = np.array(["#C7E9B4", "#7FCDBB", "#41B6C4", "#1D91C0", "#225EA8", "#0C2C84"])
ix = [0, 1, 2]
colorsd = cm[ix]
# source = ColumnDataSource(data=dict(factor=factor, normalized_values=normalized_values))
source = ColumnDataSource(dict(
    x=[0.5, 1.5, 2.5],
    y=[0, 0, 0],
    xm01=[0.5, 1.5, 2.5],
    ym01=normalized_values,
    colors=["#C7E9B4", "#7FCDBB", "#41B6C4"]
)
)

p = figure(x_range=factor, plot_height=700, plot_width=800, toolbar_location=None)
r = Segment(x0='x', y0='y', x1='xm01', y1='ym01', line_width=150, line_color='colors')
p.add_glyph(source, r)

p.xgrid.grid_line_color = None
p.y_range.start = 0
p.y_range.end = 2
p.title.text_font_size = "50px"
priceCalculator = PriceCalculator('apple')
priceCalculator.update_input(values[0], values[1], values[2])
priceCalculator.calculate_discount()
priceCalculator.calculate_price()
p.title.text = "The resulting price is ${0:.2f}".format(priceCalculator.price)
p.legend.orientation = "horizontal"
p.legend.location = "top_center"
p.legend.label_text_font_size = "15pt"
p.add_layout(Title(text="Normal price is $1.50.", text_font_size="50px"), 'above')
Beispiel #15
0
    def add_path(self,
                 source_label,
                 links=None,
                 edge_type='curved',
                 tooltips=None,
                 legend=None,
                 **kwargs):
        """
        Connect all points in the datasource in a path (to show order).
        `self.prepare_plot` must have been called previous to this.
        
        Parameters:
        
        source_label (str): string corresponding to a label previously 
            called in `self.add_source`
        order_col: the column of a data source specifying the order of the records
        tooltips: string or list of tuples (passed to Bokeh HoverTool)
        legend (str): name to assign to this layer in the plot legend
        kwargs: options passed to the objected for `bokeh_model`
        
        This method allows two special kwargs: 'color' and 'alpha'. When 
            used with a bokeh model that has 'fill_color' and 'line_color' 
            and 'fill_alpha' and 'line_alpha' properties, calling the special 
            kwarg will use the same value for both.
        
        """

        self._validate_workflow('add_path')

        source = self.sources[source_label].copy()

        suffix = '_transform' if type(self.plot) != GMapPlot else ''
        x_point_label = 'x_coord_point{}'.format(suffix)
        y_point_label = 'y_coord_point{}'.format(suffix)

        if all(isinstance(x, (int, float)) for x in source[links].tolist()):
            x1 = source.sort_values(links)[x_point_label].values
            y1 = source.sort_values(links)[y_point_label].values
            x2 = x1[1:]
            y2 = y1[1:]
            x1 = x1[:-1]
            y1 = y1[:-1]
            x3 = (x1 + x2) / 2
            y3 = (y1 + y2) / 2
            xc = x3 + abs(y3 - y2)
            yc = y3 + abs(x3 - x2)

            new_source = {
                'x1': x1,
                'x2': x2,
                'xc': xc,
                'y1': y1,
                'y2': y2,
                'yc': yc
            }

            for c in source.columns:
                if (c not in self.omit_columns) and c not in new_source:
                    new_source[c] = source[c].values[:-1]
        elif all(
                isinstance(x, (list, tuple, set))
                for x in source[links].tolist()):
            if 'uid' not in source.columns:
                raise ValueError(
                    'Source must contain column `uid` when links is a list of iterables.'
                )

            nodes = source['uid'].tolist()
            edges = source[links].tolist()
            node_x = source.set_index('uid')[x_point_label].to_dict()
            node_y = source.set_index('uid')[y_point_label].to_dict()

            a_vals, x1, x2, y1, y2 = zip(*[(a, node_x[a], node_x[b], node_y[a],
                                            node_y[b])
                                           for a, bs in zip(nodes, edges)
                                           for b in bs])
            x1, x2, y1, y2 = array(x1), array(x2), array(y1), array(y2)
            x3 = (x1 + x2) / 2
            y3 = (y1 + y2) / 2
            xc = x3 + abs(y3 - y2)
            yc = y3 + abs(x3 - x2)

            new_source = {
                'x1': x1,
                'x2': x2,
                'xc': xc,
                'y1': y1,
                'y2': y2,
                'yc': yc
            }

            for c in source.columns:
                if (c not in self.omit_columns) and c not in new_source:
                    col_dict = source.set_index('uid', drop=False)[c].to_dict()
                    new_source[c] = [col_dict[v] for v in a_vals]
        else:
            raise ValueError(
                'Values of `links` field must be numeric or a list, set, or tuple of values from the `uid` field.'
            )

        if 'color' in kwargs.keys():
            color = kwargs.pop('color')
            for v in Quadratic.dataspecs():
                if 'color' in v:
                    kwargs[v] = color

        if 'alpha' in kwargs.keys():
            alpha = kwargs.pop('alpha')
            for v in Quadratic.dataspecs():
                if 'alpha' in v:
                    kwargs[v] = alpha

        if edge_type == 'curved':
            model_object = Quadratic(x0='x1',
                                     y0='y1',
                                     x1="x2",
                                     y1="y2",
                                     cx="xc",
                                     cy="yc",
                                     name=source_label,
                                     **kwargs)
        elif edge_type == 'straight':
            model_object = Segment(x0='x1',
                                   y0='y1',
                                   x1="x2",
                                   y1="y2",
                                   name=source_label,
                                   **kwargs)
        else:
            raise ValueError(
                'Keyword `edge_type` must be either "curved" or "straight".')

        source = ColumnDataSource(new_source, name=source_label)
        rend = self.plot.add_glyph(source, model_object)

        if legend is not None:
            li = LegendItem(label=legend, renderers=[rend])
            self.legend.items.append(li)

        if tooltips is not None:
            self.plot.add_tools(HoverTool(tooltips=tooltips, renderers=[rend]))

        return self
Beispiel #16
0
         y="y",
         length=45,
         angle=-0.7,
         line_color="#FB8072",
         line_width=2)),
    ("rect",
     Rect(x="x",
          y="y",
          width=screen(10),
          height=screen(20),
          angle=-0.7,
          fill_color="#CAB2D6")),
    ("segment",
     Segment(x0="x",
             y0="y",
             x1="xm01",
             y1="ym01",
             line_color="#F4A582",
             line_width=3)),
    ("text", Text(x="x", y="y", text=["hello"])),
    ("wedge",
     Wedge(x="x",
           y="y",
           radius=screen(15),
           start_angle=0.6,
           end_angle=4.1,
           fill_color="#B3DE69")),
]

markers = [
    ("circle", Circle(x="x", y="y", radius=0.1, fill_color="#3288BD")),
    ("circle_x",
# Start timer
t0 = time.time()
################

x_range = Range1d(0, 1)
y_range = Range1d(0, 1)
plot = Plot(x_range=x_range,
            y_range=y_range,
            plot_width=plot_width,
            plot_height=plot_height,
            title=title)
plot.add_tools(PanTool(), WheelZoomTool(), BoxZoomTool(), PreviewSaveTool(),
               ResetTool())

# edges
seg = Segment(x0="ex0", y0="ey0", x1="ex1", y1="ey1", \
        line_width="ewidth",)
seg_glyph = plot.add_glyph(esource, seg)

# circles
circ = Circle(x="x", y="y", size='size', line_color=None)
circ_glyph = plot.add_glyph(nsource, circ)

################
# End Timer
print(bokeh.__version__)
print("Time to plot with Bokeh:", time.time() - t0, "seconds")

# save
bk.output_file(htmlout, mode='cdn')

################
Beispiel #18
0
    def plot_urls(self):
        """
        Visualize crawler activity by showing the most recently crawled URLs and the fetch time.
        """

        self.session.load_document(self.document)
        plot = self.document.context.children[0]

        # don't plot if no URLs available
        if not (self.open_urls or self.closed_urls):
            return

        # x0/x0, left and right boundaries of segments, correspond to fetch time
        x0 = []
        x = []
        # y-axis, name of URL being fetched
        urls = []

        # maintain x and URL of circles in a separate list
        circles = []
        circle_urls = []

        current_time = np.datetime64(datetime.now())

        # For open URLs (not completed fetching), draw a segment from start time to now
        for url, start_t in self.open_urls.items():
            url = NutchUrlTrails.strip_url(url)
            x0.append(start_t)
            x.append(current_time)
            urls.append(url)

        # For closed URLs (completed fetching), draw a segment from start to end time, and a circle as well.
        for url, (start_t, end_t) in self.closed_urls.items():
            url = NutchUrlTrails.strip_url(url)
            x0.append(start_t)
            x.append(end_t)
            circles.append(end_t)
            urls.append(url)
            circle_urls.append(url)

        x0 = np.asarray(x0)
        x = np.asarray(x)
        circles = np.asarray(circles)

        # sort segments
        sort_index = np.argsort(x0)[::-1]
        x0 = x0[sort_index]
        x = x[sort_index]
        urls = [urls[i] for i in sort_index]

        # sort circles
        if self.closed_urls:
            circle_sort_index = np.argsort(circles)[::-1]
            circles = circles[circle_sort_index]
            circle_urls = [circle_urls[i] for i in circle_sort_index]

        # Filter to latest num_url URLs (ascending order)
        # filter segments
        active_x0 = x0[:self.num_urls]
        active_x = x[:self.num_urls]
        active_urls = urls[:self.num_urls]

        min_x = min(active_x0)
        plot.x_range.start = min_x
        plot.x_range.end = np.datetime64(datetime.now())
        plot.y_range.factors = active_urls

        # make sure these are turned back on!
        # turn y axis grid lines back on
        for r in plot.renderers:
            if type(r) == Grid:
                r.grid_line_color = 'black'
                break

        # turn tickers and their labels back on
        plot.right[0].minor_tick_line_color = 'black'
        plot.right[0].major_tick_line_color = 'black'
        plot.right[0].major_label_text_font_size = '12pt'
        plot.below[0].minor_tick_line_color = 'black'
        plot.below[0].major_tick_line_color = 'black'
        plot.below[0].major_label_text_font_size = '12pt'

        # TODO: Find a more correct way to remove old segment/circle glyphs
        if self.old_circles:
            plot.renderers.pop()
            self.old_circles = None
        if self.old_segments:
            plot.renderers.pop()
            self.old_segments = None

        segment_source = ColumnDataSource(
            dict(x0=active_x0, x1=active_x, urls=active_urls))

        self.old_segments = Segment(x0="x0",
                                    y0="urls",
                                    x1="x1",
                                    y1="urls",
                                    line_color="orange",
                                    line_width=10)
        plot.add_glyph(segment_source, self.old_segments)

        if self.closed_urls and PLOT_CIRCLES:
            # filter circles (some of these might not be displayed)
            active_circles = circles[:self.num_urls]
            active_circle_urls = circle_urls[:self.num_urls]

            circle_source = ColumnDataSource(
                dict(x=active_circles, urls=active_circle_urls))

            self.old_circles = Circle(x="x",
                                      y="urls",
                                      size=12,
                                      fill_color="green",
                                      line_color="orange",
                                      line_width=2)
            plot.add_glyph(circle_source, self.old_circles)

        self.session.store_document(self.document, dirty_only=False)
Beispiel #19
0
xdr = DataRange1d()
ydr = DataRange1d()

plot = Plot(title=None,
            x_range=xdr,
            y_range=ydr,
            plot_width=300,
            plot_height=300,
            h_symmetry=False,
            v_symmetry=False,
            min_border=0,
            toolbar_location=None)

glyph = Segment(x0="x",
                y0="y",
                x1="xm01",
                y1="ym01",
                line_color="#f4a582",
                line_width=3)
plot.add_glyph(source, glyph)

xaxis = LinearAxis()
plot.add_layout(xaxis, 'below')

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

plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

doc = Document()
doc.add_root(plot)
Beispiel #20
0
            y_end=y - x**2 / 10 + 0.5,
        ))

    output_file("segments.html")

    p = figure(plot_width=400,
               plot_height=400,
               title="title_title",
               toolbar_location=None)

    p.add_glyph(
        segment_data,
        Segment(x0="x_start",
                y0="y_start",
                x1="x_end",
                y1="y_end",
                line_color="#f4a582",
                line_width=3,
                name="the_segments"))

    p.xaxis.name = "the_xaxis"
    p.xaxis.axis_label = "xaxis_label"
    p.yaxis.name = "the_yaxis"
    p.yaxis.axis_label = "yaxis_label"
    p.title.name = "the_title"

    if p.grid[0].dimension == 0:
        p.grid[0].name = "the_x_gridlines"
        p.grid[1].name = "the_y_gridlines"
    else:
        p.grid[0].name = "the_y_gridlines"
Beispiel #21
0
def draw_highlow_segment():
    g0 = Segment(x0='T', y0='H', x1='T', y1='L', line_color='black')
    return g0
Beispiel #22
0
#alternate vol shock lists to get indices between two volume shocks
x = 0
shocks1 = list()
shocks2 = list()
for i in range(len(vol_shock)):
    if vol_shock[i] == 1:
        x = x + 1
        if x%2 == 1:
            shocks1.append(i)
        if x%2 == 0:
            shocks2.append(i)
         
#coloring between shocks1[i]  and shocks2[i]
from bokeh.plotting import figure, show        
from bokeh.models.glyphs import Segment
glyph = Segment(x0=0, y0=tcs_close[0], x1=1, y1=tcs_close[1], line_color="#f4a582", line_width=3)          
shock_col = figure()
shock_col.line(range(0,len(tcs_close)), tcs_close, line_width = 2, color = 'blue')
shock_col.add_glyph(glyph)
show(shock_col)
      

#4
#since data is of one year, 52 week moving average = data average
from bokeh.plotting import figure, show
avg = np.mean(tcs_close)
from bokeh.models import ColumnDataSource, LinearColorMapper
from bokeh.models import ColorBar
from bokeh.transform import linear_cmap
from bokeh.palettes import Spectral6