Exemple #1
0
def make_plot(data):
    # Make the API request and load json data into DataFrame
    symbol = 'amzn'
    res = requests.get(API_URL.format(symbol))
    data = res.json()
    df = pd.DataFrame(data)
    # Add a new column in the shape of the original data
    seqs = np.arange(df.shape[0])
    df['seqs'] = pd.Series(seqs)
    # Add a mid column that is midpoint between open and close
    df['mid'] = df.apply(lambda x: (x['open'] + x['close']) / 2, axis=1)
    # Add height column after checking if close is greater than open
    df['height'] = df.apply(lambda x: x['close'] - x['open']
                            if x['close'] != x['open'] else 0.01, axis=1)
    # some stuff to format plot
    inc = df.close > df.open  # Series where stocks closed higher than they opened
    dec = df.close < df.open  # Series in which stocks closed lower than they opened
    w = .3  # line width for plot
    # some stuff to format plot
    inc = df.close > df.open  # Series where stocks closed higher than they opened
    dec = df.close < df.open  # Series in which stocks closed lower than they opened
    w = .3  # line width for plot
    # Define sources for increasing and decreasing stocks
    sourceInc = bk.ColumnDataSource(df.loc[inc])
    sourceDec = bk.ColumnDataSource(df.loc[dec])
    # Define the Bokeh tools to include in the figure
    hover = HoverTool(
        tooltips=[
            ('Date', '@date'),
            ('Low', '@low'),
            ('High', '@high'),
            ('Open', '@open'),
            ('Close', '@close'),
            ('Percent', '@changePercent')
        ]
    )
    TOOLS = [hover, BoxZoomTool(), PanTool(), ZoomInTool(),
             ZoomOutTool(), ResetTool()]
    # Define size and layout of figure
    p = bk.figure(plot_width=1200, plot_height=800, title='Amazon',
                  tools=TOOLS, toolbar_location='above')
    p.xaxis.major_label_orientation = np.pi/4
    p.grid.grid_line_alpha = w
    descriptor = Label(x=70,  y=70, text='Amazon Stock Price Over Time')
    p.add_layout(descriptor)
    # Create segments for price increases
    p.segment(df.seqs[inc], df.high[inc],
              df.seqs[inc], df.low[inc], color='green')
    # Create segments for price decreases
    p.segment(df.seqs[dec], df.high[dec],
              df.seqs[dec], df.low[dec], color='red')
    # Create rects for price increases
    p.rect(x='seqs', y='mid', width=w, height='height',
           fill_color='green', line_color='green', source=sourceInc)
    # Create rects for price decreases
    p.rect(x='seqs', y='mid', width=w, height='height',
           fill_color='red', line_color='red', source=sourceDec)
    script, div = components(p)
    return script, div
    def list(self, request, symbol=None):
        
        API_URL = 'https://api.iextrading.com/1.0'
        res = requests.get(f'{API_URL}/stock/'f'{symbol}/chart/5y')
        
        data = res.json()
        df = pd.DataFrame(data)

        # Candlestick chart setup
        seqs = np.arange(df.shape[0])
        df['seqs'] = pd.Series(seqs)

        df['changePercent'] = df['changePercent'].apply(lambda x: str(x)+'%')

        df['mid'] = df.apply(lambda x: (x['open'] + x['close']) / 2, axis=1)

        df['height'] = df.apply(
            lambda x: x['close'] - x['open'] if x['close'] != x['open'] else 0.001, 
            axis=1)
        inc = df.close > df.open
        dec = df.close < df.open
        w = .3

        sourceInc = bk.ColumnDataSource(df.loc[inc])
        sourceDec = bk.ColumnDataSource(df.loc[dec])

        hover = HoverTool(
            tooltips=[
                ('date', '@date'),
                ('low', '@low'),
                ('high', '@high'),
                ('open', '@open'),
                ('close', '@close'),
                ('percent', '@changePercent'),
            ]
        )
        TOOLS = [hover, BoxZoomTool(), PanTool(), ZoomInTool(), ZoomOutTool(), ResetTool()]

        p = bk.figure(plot_width=1500, plot_height=800, tools=TOOLS, title=symbol, toolbar_location='above')

        p.xaxis.major_label_orientation = np.pi/4
        p.grid.grid_line_alpha = w

        descriptor = Label(x=70, y=70, text='Your label goes here')
        p.add_layout(descriptor)

        p.segment(df.seqs[inc], df.high[inc], df.seqs[inc], df.low[inc], color='green')
        p.segment(df.seqs[dec], df.high[dec], df.seqs[dec], df.low[dec], color='red')
        p.rect(x='seqs', y='mid', width=w, height='height', fill_color='green', line_color='green', source=sourceInc)
        p.rect(x='seqs', y='mid', width=w, height='height', fill_color='red', line_color='red', source=sourceDec)
        bk.save(p, './static/candle_stick.html', title='5yr_candlestick')

        return Response(bk.show(p))
Exemple #3
0
 def source(self):
     return bokeh_plotting.ColumnDataSource(data=dict(
         x=[datum['x'] for datum in self.data],
         y=[datum['y'] for datum in self.data],
         time=[datum['time'] for datum in self.data],
         count=[datum['count'] for datum in self.data],
     ))
Exemple #4
0
def plot_stocks(df, ticker):
    """
    :param df: the pandas data frame with the stock data and datatables
    :param ticker: the name of the company (used in title)

    :return: script and div elements for a bokeh based plot
    """
    title = 'Closing prices for: ' + ticker
    f = bk.figure(title=title, x_axis_type='datetime')
    f.xaxis.axis_label = 'Date'
    f.yaxis.axis_label = 'Closing Price (USD)'

    source = bk.ColumnDataSource(data=dict(x=df['date'], y=df['price']))

    hover = HoverTool(tooltips=[
        ('Date:', '@x{%F}'),
        ('Price:', '@y{($ 0.00 a)}'),
    ],
                      formatters={
                          'x': 'datetime',
                          'y': 'numeral'
                      })
    f.add_tools(hover)

    f.line('x', 'y', source=source)

    return components(f)
Exemple #5
0
def _plot_interactive(fig,
                      df,
                      images,
                      cmap,
                      vmin,
                      vmax,
                      name=None,
                      color='blue'):
    data = df.to_dict(orient='list')
    data['images'] = [
        _serialize_image(image.T, cmap=cmap, vmin=vmin, vmax=vmax)
        for image in images
    ]
    source = bplt.ColumnDataSource(data=data)
    if not isinstance(name, str):
        try:
            name = ', '.join(name)
        except TypeError:
            name = str(name)

    fig.circle('x',
               'y',
               size=10,
               source=source,
               color=color,
               legend=name,
               muted_color=color,
               muted_alpha=0.2)
Exemple #6
0
def plot(data, x_axis, y_axis, group_by):
    fig = plotting.figure(
        sizing_mode='stretch_both',  # title=figure_name,
        x_axis_label=x_axis,
        y_axis_label=y_axis,
        tools=[
            'hover', 'crosshair', 'wheel_zoom', 'box_zoom', 'pan', 'save',
            'resize', 'reset'
        ])

    with fetch_data(data, x_axis, y_axis, group_by) as store_data:
        for i, group in enumerate(store_data):
            color = __COLORS__[i % len(__COLORS__)]
            data_source = plotting.ColumnDataSource(store_data[group])
            group_key = group[1:]  # Remove leading "/"
            fig.line(source=data_source,
                     x=x_axis,
                     y=y_axis,
                     line_width=2,
                     legend=group_key,
                     color=color,
                     muted_alpha=0.2)

    fig.legend.click_policy = "hide"

    html_file_path = data.export_file_path("html", "line", x_axis, y_axis)
    plotting.output_file(html_file_path,
                         title=data.name,
                         mode='inline',
                         root_dir=None)
    save(fig)
    js, div = components(fig, wrap_script=False, wrap_plot_info=True)
    return js, div
Exemple #7
0
def mark_3m_walk():
    global pdf_results
    selected_indices = colsource.selected.indices
    pdf_results = pdf_results.loc[~(
        (pdf_results['fname'] == file_picker.value) &
        (pdf_results['artifact'] == '3m_walk'))]
    pdf_results = pdf_results.append(
        pd.DataFrame(
            {
                'fname':
                file_picker.value,
                'artifact':
                '3m_walk',
                'start_time':
                colsource.data['timestamp'][selected_indices[0]],
                'end_time':
                colsource.data['timestamp'][selected_indices[-1]],
                'start_time_str':
                colsource.data['timestamp_str'][selected_indices[0]],
                'end_time_str':
                colsource.data['timestamp_str'][selected_indices[-1]],
            },
            index=[0]))
    annotations.data.update(bp.ColumnDataSource(pdf_results).data)
    if not btn_3m_walk.label.endswith('(done)'):
        btn_3m_walk.label = btn_3m_walk.label + ' (done)'
Exemple #8
0
def convert_to_source(hover_labels, hover_values):
    data = dict()
    for i in range(len(hover_labels)):
        data[hover_labels[i]] = hover_values[i]

    source = bkh.ColumnDataSource(
        data=data)

    return source
    def create_plot(self, counties):
        filename = self.create_filename()
        bp.output_file(filename, title=self.title)
        p = bp.figure(title=self.title,
                      x_axis_type="datetime",
                      width=1200,
                      height=700)
        legend_items = []
        for a, b in counties:
            if self.dublin == False and a == "Dublin":
                continue
            temp = b.copy()
            temp['StrDate'] = temp['TimeStamp'].apply(
                lambda x: x.strftime("%a, %b %d"))
            source = bp.ColumnDataSource(temp)
            leg = p.line("TimeStamp",
                         self.metric,
                         source=source,
                         line_width=2,
                         line_color=self.counties[a]['color'],
                         line_dash=self.counties[a]['dash'])
            legend_items.append((a, [leg]))

        legend = bm.Legend(items=legend_items,
                           location='top_right',
                           orientation='vertical',
                           border_line_color="black")

        p.add_layout(legend, 'right')

        p.legend.click_policy = "hide"
        p.legend.label_text_font_size = '12px'
        p.legend.label_text_font = 'Helvetica'
        p.legend.location = "top_left"
        p.legend.background_fill_color = 'slategray'
        p.legend.background_fill_alpha = 0.5

        tools = bm.HoverTool(
            tooltips=[("Date", "@StrDate"), (
                "County",
                "@CountyName"), ("Cases", "@ConfirmedCovidCases{0, 0}")])
        p.add_tools(tools)

        p.title.text_font = "Helvetica"
        p.title.text_font_size = "18px"

        p.background_fill_color = 'slategray'
        p.background_fill_alpha = 0.5

        p.xaxis.formatter = bm.DatetimeTickFormatter(months=["%b, %Y"],
                                                     days=["%b, %d"],
                                                     hours=["%H:%M"])

        bp.show(p)
Exemple #10
0
def get_peaks_source(peaks,
                     relative_start=0,
                     time_scaler=1,
                     keep_amplitude_per_sample=True):
    """
    Computes bokeh.plotting.ColumnDataSource for given peaks.

    :param peaks: Peaks to be plotted.
    :param relative_start: t0 from which on the peaks should be plotted.
    :param time_scaler: Factor to rescale the time from ns to other scale.
        E.g. =1000 scales to µs.
    :param keep_amplitude_per_sample: Boolean if true amplitude of the
        plotted peaks is in pe/sample. False pe/ns.
    :return: bokeh.plotting.ColumnDataSource instance which can be used
        to plot peaks.
    """
    if not (np.all(peaks['type'] == peaks[0]['type'])):
        raise ValueError(
            'All peaks must be of the same type (S1, S2 or Unknown)!')

    x_p = []
    y_p = []
    for ind, p in enumerate(peaks):
        x, y = _patches_x_y(
            p, keep_amplitude_per_sample=keep_amplitude_per_sample)
        x -= relative_start  # relative to first peak
        x = x / time_scaler
        x_p.append(x)
        y_p.append(y)

    if peaks[0]['type'] == 2:
        scaler = 10**-3
    else:
        scaler = 1

    source = bklt.ColumnDataSource(
        data={
            'xs': x_p,  # Coordinates for peak patches
            'ys': y_p,
            'x': peaks['x'],  # XY-Pos in PMZ Hitpattern
            'y': peaks['y'],
            'dt': peaks['dt'],
            'time': peaks['time'],
            'center_time': peaks['center_time'],
            'endtime': strax.endtime(peaks),
            'width_50': peaks['range_50p_area'] * scaler,
            'width_90': peaks['range_90p_area'] * scaler,
            'rise': peaks['rise_time'] * scaler,
            'rel_center_time': (peaks['center_time'] - peaks['time']) * scaler,
            'area': peaks['area'],
            'aft': peaks['area_fraction_top'],
            'nhits': peaks['n_hits'],
        })
    return source
Exemple #11
0
    def line(self,
             width=DEFAULT_WIDTH,
             height=DEFAULT_HEIGHT,
             fig=None,
             **kwds):
        """Line plot for series data.

        Parameters
        ----------
        width : int, optional
            The width of the plot in pixels.
        height : int, optional
            The height of the plot in pixels.
        fig : Figure, optional
            If specified, the line is added to the existing figure.
        **kwds :
            Extra keywords passed to ``line``.

        Examples
        --------

        >>> series.plot.line(color='blue', alpha=0.5)  # doctest: +SKIP

        Returns
        -------
        fig : bokeh.plotting.Figure
        """
        df = self._data.reset_index()

        x, y = df.columns = [str(c) for c in df.columns]

        x_data = df[x]
        y_data = df[y]

        axis_kwargs = {}
        for axis, data in [('x', x_data), ('y', y_data)]:
            if is_datetime64_any_dtype(data.dtype):
                axis_kwargs['%s_axis_type' % axis] = 'datetime'
            elif is_categorical_dtype(data.dtype):
                raise ValueError("Categorical dtype not supported for line")

        source = bp.ColumnDataSource({x: x_data, y: y_data})

        if fig is None:
            fig = bp.Figure(plot_height=height,
                            plot_width=width,
                            **axis_kwargs)

        fig.line(x, y, source=source, **kwds)

        return fig
Exemple #12
0
def make_bokeh_plot(comps, recipe_names, description_strings):
    colors = color_values[~masked_recipes.mask.all(axis=1)]
    data_source = dict(
        colors=colors,
        x=comps[:, 0],
        y=comps[:, 1],
        images=[
            picture_urls[i]
            for i in np.where(~masked_recipes.mask.all(axis=1))[0]
        ],
        desc=recipe_names,
        labels=alcohol_names[~masked_recipes.mask.all(axis=1)],
        ingredients=description_strings)
    source = bpl.ColumnDataSource(data_source)
    TOOLTIPS = """
        <div style="border: none !important">
        <div>
            <div>
                <img
                    src="@images" height="150" alt="@images" width="150"
                    style="float: left; margin: 0px 15px 15px 0px;"
                    border="2"
                ></img>
            </div>
            <div>
                <br>
                <span style="font-size: 17px; font-weight: bold;">@desc</span>
            </div>
            <div>
            <br>
                <span>@ingredients{safe}</span>
            </div>
        </div>
    """
    p = bpl.figure(tools="reset,pan,wheel_zoom", tooltips=TOOLTIPS)

    p.scatter('x',
              'y',
              marker='o',
              size=10,
              fill_color='colors',
              source=source,
              color='colors',
              legend='labels')
    p.axis.visible = False
    p.title.text = "Unsupervised Cocktails"
    p.title.text_color = "white"
    p.title.text_font_size = "40px"
    p.legend.location = "top_left"
    return p, source
Exemple #13
0
def plot_patches_on_gmap(vertex_xcoords,
                         vertex_ycoords,
                         api_key,
                         solid_fill=None,
                         values=None,
                         color_mapper=None,
                         map_options=None,
                         title=None,
                         alpha=0.25):

    if values is not None:
        assert color_mapper is not None, "must provide a color_mapper if providing a list of colors"
    else:
        assert solid_fill is not None, "must provide a solid fill color if not providing a list of colors"

    plot = bk.gmap(api_key, map_options=map_options, title=title)
    plot.add_tools(PanTool(), WheelZoomTool(), ResetTool())

    data = dict(xs=vertex_xcoords, ys=vertex_ycoords)
    if values is not None:
        data['colors'] = values

    source_patches = bk.ColumnDataSource(data=data)

    if values is not None:
        patches_glyph = plot.patches('xs',
                                     'ys',
                                     fill_alpha=alpha,
                                     fill_color={
                                         "field": "colors",
                                         "transform": color_mapper
                                     },
                                     source=source_patches,
                                     line_width=0)

        color_bar = ColorBar(color_mapper=color_mapper,
                             border_line_color=None,
                             location=(0, 0),
                             scale_alpha=alpha,
                             title="minutes")
        plot.add_layout(color_bar, 'right')
    else:
        patches_glyph = plot.patches('xs',
                                     'ys',
                                     fill_alpha=alpha,
                                     fill_color=solid_fill,
                                     source=source_patches,
                                     line_width=0)

    return plot
Exemple #14
0
def plot_true_and_estimated_channel_with_bokeh(true_channel,
                                               estimated_channel,
                                               title='',
                                               antenna=0):
    true_channel_time = np.fft.ifft(true_channel[:, antenna], axis=0)

    num_subcarriers = true_channel.shape[0]

    data = {
        'index': np.r_[0:num_subcarriers],
        'channel_time': np.abs(true_channel_time),
        'channel': np.abs(true_channel[:, antenna]),
        'estimated_channel': np.abs(estimated_channel[:, antenna]),
        'error': linear2dB(
            np.abs(true_channel[:, antenna] - estimated_channel[:, antenna]) / \
            np.abs(true_channel[:, antenna]))}
    source00 = bp.ColumnDataSource(data=data)

    # Specify the tools by name. This does not allow us to set parameters
    # for the tools
    TOOLS = "pan,wheel_zoom,box_zoom,reset,resize,crosshair"
    # Create a hover tool and tell it to only show for a curve with name
    # 'estimated'
    hover_tool = HoverTool(names=['estimated'],
                           tooltips=[('True Channel', ''),
                                     ('Error (in dB)', '@error')])
    # p1 = bp.figure(tools=TOOLS, width=600, height=200)
    # p1.circle('index', 'channel_time', source=source00)
    # p1.title = title

    p2 = bp.figure(tools=TOOLS, plot_width=400, plot_height=300)
    p2.add_tools(hover_tool)

    p2.line('index', 'channel', source=source00, legend='True Channel')
    # We specify the 'name' attribute so that we can specify the 'names'
    # attribute for the hover tool and tell it to only show for the
    # estimated channel curve.
    p2.line('index',
            'estimated_channel',
            source=source00,
            color='red',
            name='estimated',
            legend='Estimated Channel')

    p2.title = title

    # p = bp.vplot(p1, p2)
    # return p
    return p2
Exemple #15
0
def user_hist_monthly(data):
    ds = bplt.ColumnDataSource(
        data=dict(month=[datum.date_label for datum in data],
                  count=[len(datum.df.UserId.unique()) for datum in data]))
    hover = bmodels.HoverTool(tooltips=[('month',
                                         '@month'), ('num users', '@count')])
    fig = bplt.figure(plot_width=900,
                      plot_height=600,
                      x_range=ds.data['month'],
                      x_axis_label='Month',
                      y_axis_label='Number of Users',
                      tools=[hover],
                      title='Num Users vs Month')
    fig.vbar(x='month', top='count', bottom=0, width=0.5, source=ds)
    bplt.show(fig)
Exemple #16
0
def visualize_clusters(peaklistpath, plotfilepath, title, x, y):
    """Visualize cluster in 2D space."""

    TOOLS = "pan,box_zoom,box_select,resize,reset,wheel_zoom,save"
    bkp.output_file(plotfilepath)
    plot = bkp.figure(tools=TOOLS, title=title)

    plot.xaxis.axis_label, plot.yaxis.axis_label = "{}, ppm".format(
        x), "{}, ppm".format(y)

    for cluster, color in zip(
            grouping.DBSCAN.global_clusters[peaklistpath].values(), COLOR_HEX):
        x_coords = cluster.coordinates(x)
        y_coords = cluster.coordinates(y)
        assignments = cluster.assignments()
        source = bkp.ColumnDataSource(
            data=dict(x=x_coords, y=y_coords, assignment=assignments))

        for point in cluster.members:
            if cluster.label == -1:
                g = bkm.CircleX(x='x',
                                y='y',
                                line_color='#6666ee',
                                fill_color='black',
                                fill_alpha=0.5,
                                size=5)
            else:
                g = bkm.Circle(x='x',
                               y='y',
                               line_color='#6666ee',
                               fill_color=color,
                               fill_alpha=0.5,
                               size=10)

            gr = plot.add_glyph(source_or_glyph=source, glyph=g)
            g_hover = bkm.HoverTool(renderers=[gr],
                                    tooltips=[('x', '@x'), ('y', '@y'),
                                              ('assignment', '@assignment')])
            plot.add_tools(g_hover)

        plot.text(np.mean(x_coords),
                  np.mean(y_coords),
                  text=[cluster.label],
                  text_color='black',
                  text_align='center',
                  text_font_size='10pt')
    # bkp.show(plot)
    bkp.save(plot)
Exemple #17
0
def plot_parameters(parameters, **kwargs):
    """
   Makes a simple plot of the given parameters
   """
    xpar = parameters.get('xaxis', 'p')
    ypar = parameters.get('yaxis', 'e')

    data, parameters = get_data(parameters)
    statistics = get_parameter_statistics(data, parameters)

    #-- datasource for bokeh
    datasource = bpl.ColumnDataSource(data=data)


    tooltips = [('System', '@system')] + \
               [(p, '@{} +- @e_{}'.format(p, p)) for p in parameters]
    hover = mpl.HoverTool(tooltips=tooltips)

    TOOLS = [
        mpl.PanTool(),
        mpl.WheelZoomTool(),
        mpl.BoxZoomTool(),
        mpl.ResetTool(), hover
    ]

    fig = bpl.figure(plot_width=800,
                     plot_height=600,
                     toolbar_location='right',
                     tools=TOOLS)

    fig.circle(xpar, ypar, source=datasource, size=5)
    #    Make sure xpar is filled otherwise avoid plotting
    if xpar != '':
        plot_errorbars(fig,
                       data[xpar],
                       data[ypar],
                       xerr=data['e_' + xpar],
                       yerr=data['e_' + ypar])

    fig.toolbar.logo = None
    fig.yaxis.axis_label = ypar
    fig.xaxis.axis_label = xpar
    fig.yaxis.axis_label_text_font_size = '10pt'
    fig.xaxis.axis_label_text_font_size = '10pt'
    fig.min_border = 5

    return fig, statistics
def plot(proj_lda, docs, company_names, five_highest_topics, year_values,
         nb_samples, title, colors, color_keys, filename, nb_topics):
    # Plot
    plot_lda = bp.figure(
        plot_width=1820,
        plot_height=950,
        title=title + ' ({} sample{}, {} topics)'.format(
            nb_samples, 's' if nb_samples > 1 else '', nb_topics),
        tools="pan,wheel_zoom,box_zoom,reset,hover,previewsave",
        x_axis_type=None,
        y_axis_type=None,
        min_border=1)

    plot_lda.scatter(
        x=proj_lda[:nb_samples, 0],
        y=proj_lda[:nb_samples, 1],
        color=colors[color_keys][:nb_samples],
        source=bp.ColumnDataSource({
            "X":
            proj_lda[:nb_samples, 0],
            "Y":
            proj_lda[:nb_samples, 1],
            "5_highest_topics":
            five_highest_topics[:nb_samples]
            if nb_samples > 1 else [five_highest_topics[:nb_samples]],
            "year":
            year_values[:nb_samples]
            if nb_samples > 1 else [year_values[:nb_samples]],
            "file":
            docs[:nb_samples] if nb_samples > 1 else [docs[:nb_samples]],
            "company":
            company_names[:nb_samples]
            if nb_samples > 1 else [company_names[:nb_samples]]
        }))

    # Hover tool
    hover = plot_lda.select(dict(type=HoverTool))
    hover.tooltips = {
        "X": "@X",
        "Y": "@Y",
        "Year": "@year",
        "5 highest topics": "@5_highest_topics",
        "Filename": "@file",
        "Company": "@company"
    }

    save(plot_lda, '{}.html'.format(filename))
Exemple #19
0
def hoverPlot(DataFrame, ID, x, y, plotname='temp_intr_plot'):
    source = bp.ColumnDataSource(data=DataFrame)
    bp.output_file('{}.html'.format(plotname))
    hover = bm.HoverTool()
    hover.tooltips = [
        (
            ID, '@{{{}}}'.format(ID)
        ),  # this {{{ }}} shenanigans are to scape ( {{ ) a  curly brace on either side
        (x, '@{{{}}}'.format(x)),
        (y, '@{{{}}}'.format(y))
    ]

    fig = bp.figure(
        plot_width=800,
        plot_height=800,
        title=plotname,
        toolbar_location="right",
        toolbar_sticky=False,
        tools=[hover, bm.PanTool(),
               bm.WheelZoomTool(),
               bm.ResetTool()])
    # scatter
    fig.circle(x, y, size=10, color='black', source=source)

    # trendline
    linfit = stats.linregress(DataFrame[x], DataFrame[y])
    legend = 'slope: {} \n rvalue: {} \n pvalue {}'.format(
        linfit.slope, linfit.rvalue, linfit.pvalue)

    def linfunct(a):
        return a * linfit[0] + linfit[1]

    min = DataFrame[x].min()
    max = DataFrame[x].max()

    fig.line([min, max], [linfunct(min), linfunct(max)],
             color='red',
             legend=legend)

    # Formating
    fig.legend.location = 'top_left'
    fig.xaxis.axis_label = x
    fig.yaxis.axis_label = y

    bp.show(fig)
Exemple #20
0
    def _plot_bokeh(self, current_plot, show_legend=True):
        from bokeh.models.tools import HoverTool
        from collections import OrderedDict
        import bokeh.plotting as bkh

        value_lst = self.matrix.flatten()
        min_el = min(value_lst)
        vmax = float(max(value_lst) - min_el)
        color_lst = [BOKEH_CMAP[int((v - min_el) / vmax * (len(BOKEH_CMAP) - 1))] \
                     for v in value_lst]

        source = bkh.ColumnDataSource(data=dict(
            x=self.labels * self.matrix.shape[0],
            y=numpy.array([[i] * self.matrix.shape[1]
                           for i in self.labels]).flatten(),
            color=color_lst,
            value=value_lst,
        ))
        # current_plot._below = []
        current_plot.x_range = bkh.FactorRange(factors=self.labels)
        current_plot.y_range = bkh.FactorRange(factors=self.labels)
        # current_plot._left = []

        # current_plot.extra_y_ranges = {"foo": bkh.FactorRange(factors=self.labels)}
        # current_plot.add_layout(CategoricalAxis(y_range_name="foo"), place='left')
        # current_plot.extra_x_ranges = {"foo": bkh.FactorRange(factors=self.labels)}
        # current_plot.add_layout(CategoricalAxis(x_range_name="foo"), place='top')

        current_plot.rect('x',
                          'y',
                          0.98,
                          0.98,
                          source=source,
                          color='color',
                          line_color=None)
        current_plot.grid.grid_line_color = None
        current_plot.axis.axis_line_color = None
        current_plot.axis.major_tick_line_color = None
        hover = current_plot.select(dict(type=HoverTool))
        if hover == []:
            hover = HoverTool(plot=current_plot, always_active=True)
        hover.tooltips = OrderedDict([('labels', '@x @y'),
                                      ('value', '@value')])
        current_plot.tools.append(hover)
        return current_plot
    def create_plot(self, data):
        filename = self.create_filename()
        bp.output_file(filename, title=self.title)
        p = bp.figure(title=self.title,
                      x_axis_type="datetime",
                      width=1200,
                      height=700)
        temp = data.copy()
        temp['StrDate'] = temp['TimeStamp'].apply(
            lambda x: x.strftime("%a, %b %d"))
        temp['Base'] = 0
        source = bp.ColumnDataSource(temp)
        p.varea("TimeStamp",
                "Daily",
                "Base",
                source=source,
                fill_color="pink",
                fill_alpha=0.5,
                legend_label="Daily Cases")

        p.line("TimeStamp",
               "Average",
               source=source,
               line_width=3,
               line_color="crimson",
               legend_label="Average Daily Cases")

        tools = bm.HoverTool(tooltips=[("Date", "@StrDate"),
                                       ("Daily Cases", "@Daily{0, 0}"),
                                       ("Average Cases", "@Average{0, 0}")],
                             mode="vline")
        p.add_tools(tools)

        p.legend.location = "top_left"
        p.legend.click_policy = "hide"

        p.title.text_font = "Helvetica"
        p.title.text_font_size = "18px"
        p.background_fill_color = 'slategray'
        # p.background_fill_alpha = 0.25
        p.xaxis.formatter = bm.DatetimeTickFormatter(months=["%b, %Y"],
                                                     days=["%b, %d"],
                                                     hours=["%H:%M"])

        bp.show(p)
Exemple #22
0
def make_data(country_list, country_rank_df):

    p = figure(plot_width=600, plot_height=600)

    for i in range(len(country_list)):

        data = bp.ColumnDataSource(
            data={
                'year':
                country_rank_df.loc[country_rank_df.country_name ==
                                    country_list[i]].year,
                'group':
                country_rank_df.loc[country_rank_df.country_name ==
                                    country_list[i]].country_name,
                'score':
                country_rank_df.loc[country_rank_df.country_name ==
                                    country_list[i]].score
            })

        view = CDSView(source=data,
                       filters=[
                           GroupFilter(column_name='country_name',
                                       group=country_list[i])
                       ])

        p.line('year',
               'score',
               source=data,
               view=view,
               line_width=2,
               color=(Category10[3])[i],
               legend=country_list[i])

    hover = HoverTool(tooltips=[('Score', '@score')])

    checkbox_group = CheckboxGroup(labels=list(
        country_rank_df.country_name.unique()),
                                   active=[0, 1])

    p.add_tools(hover)

    layout = row(p, checkbox_group)

    return layout
Exemple #23
0
def get_filedata(fname):
    """This function accepts a filename as input and returns the passed file's timestamp index & ColumnDataSource version of the file data
      :param fname str: signal filename
      :return: numpy.ndarray, bokeh.models.ColumnDataSource
    """
    df_signal = pd.read_csv(url + '/' + fname)
    # print("First few rows in the loaded file:")
    # print(df_signal.head())

    df_signal = df_signal.assign(
        timestamp=pd.to_datetime(df_signal['timestamp']),
        timestamp_str=pd.to_datetime(df_signal['timestamp']).astype(str))
    print("Column datatypes:")
    print(df_signal.head().dtypes)

    dates = df_signal['timestamp'].values
    source = bp.ColumnDataSource(df_signal)

    return dates, source
def plot(proj_tsne, vocabulary, wv, ws, nb_samples, title, colors, color_keys, filename):
    # Plot
    plot_we = bp.figure(plot_width=1820, plot_height=950,
                         title=title + ' ({} words of dim {}, {} sentiment categories)'.format(nb_samples, len(wv[0]), len(set(ws))),
                         tools="pan,wheel_zoom,box_zoom,reset,hover,previewsave",
                         x_axis_type=None, y_axis_type=None, min_border=1)

    plot_we.scatter(x=proj_tsne[:nb_samples, 0], y=proj_tsne[:nb_samples, 1],
                     color=colors[color_keys][:nb_samples],
                     source=bp.ColumnDataSource({
                         "word": vocabulary[:nb_samples],
                         "sentiment": ws[:nb_samples]
                     })
                     )

    # Hover tool
    hover = plot_we.select(dict(type=HoverTool))
    hover.tooltips = {"Word": "@word", "Sentiment": "@sentiment"}

    save(plot_we, '{}.html'.format(filename))
Exemple #25
0
def plot_correlation(fig,
                     correlation_series,
                     correlation_colors=['green', 'red'],
                     averaging_window=DEFAULT_AVERAGING_WINDOW):
    ''' Add colored correlation plots to the figure.

    The correlation will be displayes with two colors depending on its sign.
    The correlation time series is assumed to be datetime indexed, and is
    averaged with a rolling time window.

    Args:
        fig: bokeh figure.
        correlation_series: pandas series of corrleations.
        correlation_colors: list of colors representing positive and
            negative respectively.
        averaging_window: width of the rolling time average window.
    Returns:
        Modified Bokeh figure.
    '''
    corr_avg = correlation_series.rolling(window=averaging_window,
                                          center=True).mean()
    # Do not show negative values in the positive part.
    corr_avg_pos = corr_avg.copy()
    corr_avg_pos[corr_avg_pos < 0] = np.nan

    # Do not show positive values in the negative part.
    corr_avg_neg = corr_avg.copy()
    corr_avg_neg[corr_avg_pos >= 0] = np.nan

    source = plt.ColumnDataSource(
        data=dict(series_avg=[corr_avg_pos, corr_avg_neg],
                  date=[corr_avg_pos.index, corr_avg_neg.index],
                  color=['green', 'red']))
    # add a line renderer with legend and line thickness
    fig.multi_line('date',
                   'series_avg',
                   source=source,
                   color='color',
                   hover_line_color='color',
                   legend='Correlation')
    return fig
Exemple #26
0
def plot_series(fig,
                pandas_dataframe,
                averaging_window=DEFAULT_AVERAGING_WINDOW):
    ''' Add time series plots to the figure.

    The time series are assumed to be datetime indexed, and are
    averaged with a rolling time window.

    Args:
        fig: bokeh figure.
        pandas_dataframe: data frame indexed by datetime,
            each column is a new time series.
        averaging_window: width of the rolling time average window.
    Returns:
        Modified Bokeh figure.
    '''
    dates = pandas_dataframe.index
    for (series_name, series), color in zip(pandas_dataframe.iteritems(),
                                            pal.Spectral11):
        # Rolling average of the series.
        series_avg = series.rolling(window=averaging_window,
                                    center=True).mean()

        source = plt.ColumnDataSource(
            data=dict(series_avg=series_avg, date=dates))
        fig.line('date',
                 'series_avg',
                 source=source,
                 legend=series_name,
                 color=color)

    # create a datetime tooltip
    hover = bmod.HoverTool(
        line_policy='next',
        tooltips=[('date', '@date{%F}'), ('growth', '$y')],
        formatters={'date': 'datetime'},
    )

    fig.add_tools(hover)
    return fig
def plot_embedding(X_emb, labels, named_labels):
    # 20 colors
    colormap = np.array([
        "#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c", "#98df8a",
        "#d62728", "#ff9896", "#9467bd", "#c5b0d5", "#8c564b", "#c49c94",
        "#e377c2", "#f7b6d2", "#7f7f7f", "#c7c7c7", "#bcbd22", "#dbdb8d",
        "#17becf", "#9edae5"
    ])

    plot_fig = bp.figure(
        plot_width=700,
        plot_height=500,
        tools="pan, wheel_zoom, box_zoom, reset, hover, previewsave",
        x_axis_type=None,
        y_axis_type=None,
        min_border=1)

    data_dict = {
        'x': X_emb[:, 0],
        'y': X_emb[:, 1],
        'color': colormap[labels],
        'label': named_labels
    }

    mySource = bp.ColumnDataSource(data_dict)

    plot_fig.circle(x='x',
                    y='y',
                    color='color',
                    legend='label',
                    source=mySource)
    plot_fig.legend.location = (0, 70)
    new_legend = plot_fig.legend[0]
    plot_fig.legend[0].plot = None
    plot_fig.add_layout(new_legend, 'right')
    plot_fig.legend.label_text_font_size = '7pt'

    show(plot_fig)
Exemple #28
0
def showall():
    for node in nodes:
        sql = 'SELECT * FROM {} ORDER BY id DESC LIMIT {}'.format(node,
                                                                  nvalues)
        df = pd.read_sql(sql, connection)
        ds = bp.ColumnDataSource(df)
        tl[node] = bp.figure(x_axis_type='datetime',
                               width=graphwidth,
                               height=graphheight,
                               title='{} - Temperature'.format(node))
        tl[node].y_range = Range1d(temperature_low, temperature_high)
        tl[node].line(source=ds, x='ts', y='temperature')
        hl[node] = bp.figure(x_axis_type='datetime',
                               width=graphwidth,
                               height=graphheight,
                               title='{} - Humidity'.format(node))
        hl[node].y_range = Range1d(humidity_low, humidity_high)
        hl[node].line(source=ds, x='ts', y='humidity', line_color="green")

    gpl = []
    for node in nodes:
        gpl.append([tl[node],hl[node]])
    output_file("layout.html")
    show(bp.gridplot(gpl))
Exemple #29
0
    def bokeh_plot(self):
        if self._bokeh_plot is None:
            spinflag = False
            if len(self.dos) == 2:
                spinflag = True

            if spinflag:
                source = bkp.ColumnDataSource(data=dict(
                    en=self.energy,
                    up=self.dos[0],
                    down=-self.dos[1],
                ))
            else:
                source = bkp.ColumnDataSource(data=dict(
                    en=self.energy,
                    dos=self.dos[0],
                ))

            p = bkp.figure(
                width=500,
                height=300,
                x_range=(-6, 6),
                tools=["pan", "box_zoom", "hover", "reset", "save", "help"],
            )

            p.title.text = "Density of States"
            p.title.align = "center"
            p.title.text_font_size = "15pt"

            p.xaxis.axis_label = "E \u2212 E_Fermi (eV)"
            p.xaxis.axis_label_text_font_size = "14pt"
            p.xaxis.major_label_text_font_size = "12pt"

            p.yaxis.axis_label = "# of states (arb. units)"
            p.yaxis.axis_label_text_font_size = "14pt"
            p.yaxis.major_label_text_font_size = "12pt"

            vline = Span(
                location=0,
                dimension="height",
                line_color="gray",
                line_width=1.5,
                line_dash="dashed",
            )
            p.renderers.extend([vline])

            if spinflag:
                p.line(
                    "en",
                    "up",
                    line_width=2,
                    line_color="blue",
                    legend="Spin Up",
                    source=source,
                )
                p.line(
                    "en",
                    "down",
                    line_width=2,
                    line_color="orange",
                    legend="Spin Down",
                    source=source,
                )
            else:
                p.line(
                    "en",
                    "dos",
                    line_width=2,
                    line_color="blue",
                    legend="total",
                    source=source,
                )

            p.legend.click_policy = "hide"
            self._bokeh_plot = p

        return self._bokeh_plot
Exemple #30
0
def plot_merged_benchmark(savefile, benchmarks, title, xaxis_type, yaxis_type,
    save_prefix=""):

    # Sort the benchmarks by device name
    bmarks_sorted = sorted(benchmarks, key=lambda k: k['extra_data']['AF_DEVICE'])
    benchmarks = bmarks_sorted

    # configure the colors
    colors = unique_colors()
    assigned_colors = dict()

    # configure the hover box
    hover = HoverTool(
        tooltips = [
            ("Device", "@device"),
            ("Benchmark", "@benchmark"),
            ("Backend", "@platform"),
            ("OS", "@os"),
            ("(x,y)", "(@x,@y)")
        ])

    # configure the plot title and axis labels, use CDN for the data source
    #bplt.output_file(save_prefix + savefile + ".html", title=title, mode='cdn')
    bplt.output_file(save_prefix + savefile + ".html", title=title)
    plot = bplt.figure(title=title, tools=[hover,'save,box_zoom,resize,reset'])
    xlabel = ""
    ylabel = ""
    legend_location = "top_right"

    # plot images/second vs. data size
    scatter_renderers = list()
    for benchmark in benchmarks:
        bmark_name = benchmark['benchmark_name']

        # Look up the color
        device = benchmark['extra_data']['AF_DEVICE']
        platform = benchmark['extra_data']['AF_PLATFORM']
        operating_system = benchmark['extra_data']['AF_OS']
#        key = device
        key = bmark_name + device + platform
        if key in assigned_colors:
            color = assigned_colors[key]
        else:
            color = colors.next()
            assigned_colors[key] = color

        # extract benchmarks
        x,xlabel,legend_location = format_data(benchmark, xaxis_type)
        y,ylabel,legend_location = format_data(benchmark, yaxis_type)
        # get the device name, override if necessary
        if 'AF_LABEL' in benchmark['extra_data'].keys():
            device = benchmark['extra_data']['AF_LABEL']

        source = bplt.ColumnDataSource(
            data = dict(x=x,y=y,
                device=[device]*len(x),
                benchmark=[bmark_name]*len(x),
                platform=[platform]*len(x),
                os=[operating_system]*len(x),
            ))

        # Generate the legend, automatically add the platform if needed
#        legend = device
        legend = device + " (" + platform + ") " + bmark_name

        # generate the plot
        plot.line(x,y, legend=legend, color=color, line_width=2)
        sr = plot.scatter('x', 'y', source=source, legend=legend, color=color,
            fill_color="white", size=8)
        scatter_renderers.append(sr)

    hover = plot.select(HoverTool)
    hover.renderers = scatter_renderers

    plot.xaxis.axis_label = xlabel
    plot.yaxis.axis_label = ylabel
    plot.legend.location = legend_location

    # save the plot
    bplt.save(plot)