Пример #1
0
    def plot_compare_recension(self, fs_dict, gs_dict, df_dict):
        """This function returns the comparison map based on the entered values as follows:
            fs_dic ~ dictionary of all coastal localities in Omega
            gs_dic ~ dictionary of all coastal localities in Xi
            df_dic ~ dictionary of all localities -->dict
            """

        tools = ["hover", "box_select", "box_zoom", "wheel_zoom", "reset"]
        TOOLTIPS = [("index", "$index"), ("(x,y)", "($x, $y)")]
        a = df_dict['dfTempX'].reset_index()
        a = a[a.longitude.apply(lambda row: row not in [0])]
        a = a.rename(columns={
            'longitude': 'longitude_Xi',
            'latitude': 'latitude_Xi'
        })
        a = a[['ID', 'longitude_Xi', 'latitude_Xi']].dropna()

        b = df_dict['dfTemp'].reset_index()
        b = b[b.longitude.apply(lambda row: row not in [0])]
        b = b.rename(columns={
            'longitude': 'longitude_Omega',
            "latitude": "latitude_Omega"
        })
        b = b[['ID', 'longitude_Omega', 'latitude_Omega']].dropna()
        c = pd.merge(left=a, right=b, how='inner')

        IbEq = c[c["longitude_Xi"] == c["longitude_Omega"]]
        IbEq = IbEq[IbEq["latitude_Xi"] == IbEq["latitude_Omega"]]

        r = figure(title='Comparison between Xi (red) and Omega (blue)',
                   width=1000,
                   height=800,
                   x_range=(1.5, 22),
                   y_range=(35.5, 47),
                   tools=tools,
                   tooltips=TOOLTIPS)
        # Xi
        Locality = {
            "x": list(self.df_dict["dfTempX"]['longitude']),
            "y": list(self.df_dict["dfTempX"]['latitude'])
        }
        source = ColumnDataSource(data=Locality)
        view = CDSView(source=source)
        r.circle(x='x',
                 y='y',
                 source=source,
                 view=view,
                 size=5,
                 fill_color='red',
                 fill_alpha=.7,
                 line_color='Crimson',
                 line_alpha=0,
                 legend="Localities (Xi)")
        for i in gs_dict.values():
            r.line(i[:, 0],
                   i[:, 1],
                   color='Crimson',
                   legend="Coasts and boundaries (Xi) ",
                   line_width=1.5)
        # Omega
        Locality = {
            "x": list(self.df_dict["dfTemp"]['longitude']),
            "y": list(self.df_dict["dfTemp"]['latitude'])
        }
        source = ColumnDataSource(data=Locality)
        view = CDSView(source=source)
        r.circle(x='x',
                 y='y',
                 source=source,
                 view=view,
                 size=5,
                 fill_color='blue',
                 fill_alpha=0.8,
                 line_color='DodgerBlue',
                 line_alpha=0,
                 legend="Localities (Omega)",
                 muted_alpha=0.2)
        for i in fs_dict.values():
            r.line(i[:, 0],
                   i[:, 1],
                   color='DodgerBlue',
                   legend="Coasts and boundaries (Omega)",
                   line_width=1.5)
        r.circle(np.array(IbEq["longitude_Xi"]),
                 np.array(IbEq["latitude_Xi"]),
                 size=5.5,
                 fill_color='green',
                 fill_alpha=1,
                 line_color='green',
                 line_alpha=0.8,
                 legend="Locality with same coordinates in Xi and Omega")
        r.segment(x0=c["longitude_Xi"],
                  y0=c["latitude_Xi"],
                  x1=c["longitude_Omega"],
                  y1=c["latitude_Omega"],
                  color="grey",
                  line_width=1,
                  legend="Distance line")
        r.legend.click_policy = "hide"
        r.legend.location = "bottom_right"
        show(r)
Пример #2
0
                           parse_dates=['gmDate'])
team_stats = pd.read_csv(WORK_DIR + '/data/2017-18_teamBoxScore.csv',
                         parse_dates=['gmDate'])
standings = pd.read_csv(WORK_DIR + '/data/2017-18_standings.csv',
                        parse_dates=['stDate'])

# Output to file
output_file('east-west-top-2-gridplot.html',
            title='Conference Top 2 Teams Wins Race')

# Create a ColumnDataSource
standings_cds = ColumnDataSource(standings)

# Create views for each team
rockets_view = CDSView(
    source=standings_cds,
    filters=[GroupFilter(column_name='teamAbbr', group='HOU')])
warriors_view = CDSView(
    source=standings_cds,
    filters=[GroupFilter(column_name='teamAbbr', group='GS')])

celtics_view = CDSView(
    source=standings_cds,
    filters=[GroupFilter(column_name='teamAbbr', group='BOS')])
raptors_view = CDSView(
    source=standings_cds,
    filters=[GroupFilter(column_name='teamAbbr', group='TOR')])

# Create and configure the figure
east_fig = figure(x_axis_type='datetime',
                  plot_height=300,
def make_cbd_plot(session,
                  current_user,
                  flight_id,
                  width,
                  height,
                  return_plot=False,
                  pageref=0,
                  dataset='antarctica',
                  flight_date=None):
    if flight_date is None:
        df = pd.read_sql(FilmSegment.query_visible_to_user(current_user, session=session).filter(FilmSegment.dataset == dataset) \
            .filter(FilmSegment.flight == flight_id).statement, session.bind)
    else:
        df = pd.read_sql(FilmSegment.query_visible_to_user(current_user, session=session).filter(FilmSegment.dataset == dataset) \
            .filter(and_(FilmSegment.flight == flight_id, FilmSegment.raw_date == flight_date)).statement, session.bind)

    # Add colormaps to plot
    unique_reels = df['reel'].unique()
    reel_map = {r: idx for idx, r in enumerate(unique_reels)}
    reel_cm = plt.cm.get_cmap('viridis', len(unique_reels))

    df['Color by Reel'] = df['reel'].apply(
        lambda x: mcolors.to_hex(reel_cm.colors[reel_map[x]]))
    df['Color by Verified'] = df['is_verified'].apply(lambda x: app.config[
        'COLOR_ACCENT'] if x else app.config['COLOR_GRAY'])
    df['Color by Review'] = df['needs_review'].apply(lambda x: app.config[
        'COLOR_ACCENT'] if x else app.config['COLOR_GRAY'])
    df['Color by Frequency'] = df['instrument_type'].apply(
        lambda x: app.config['COLOR_REDWOOD'] if x == FilmSegment.RADAR_60MHZ
        else (app.config['COLOR_PALO_ALOT']
              if x == FilmSegment.RADAR_300MHZ else app.config['COLOR_GRAY']))

    #

    source = ColumnDataSource(df)

    toggle_verified = Toggle(label="Show only verified")
    toggle_junk = Toggle(label="Hide junk", active=True)
    toggle_z = Toggle(label="Show Z Scopes", active=True)
    toggle_a = Toggle(label="Show A Scopes", active=True)

    toggle_verified.js_on_change(
        'active',
        CustomJS(args=dict(source=source), code="source.change.emit()"))
    toggle_junk.js_on_change(
        'active',
        CustomJS(args=dict(source=source), code="source.change.emit()"))
    toggle_z.js_on_change(
        'active',
        CustomJS(args=dict(source=source), code="source.change.emit()"))
    toggle_a.js_on_change(
        'active',
        CustomJS(args=dict(source=source), code="source.change.emit()"))

    filter_verified = CustomJSFilter(args=dict(tog=toggle_verified),
                                     code='''
        var indices = [];
        for (var i = 0; i < source.get_length(); i++){
            if ((!tog.active) || source.data['is_verified'][i]){
                indices.push(true);
            } else {
                indices.push(false);
            }
        }
        return indices;
    ''')
    filter_junk = CustomJSFilter(args=dict(tog=toggle_junk),
                                 code='''
        var indices = [];
        for (var i = 0; i < source.get_length(); i++){
            if (tog.active && source.data['is_junk'][i]){
                indices.push(false);
            } else {
                indices.push(true);
            }
        }
        console.log(indices);
        return indices;
    ''')
    filter_scope = CustomJSFilter(args=dict(tog_a=toggle_a, tog_z=toggle_z),
                                  code='''
        console.log('filter_scope');
        var indices = [];
        for (var i = 0; i < source.get_length(); i++){
            if (tog_a.active && (source.data['scope_type'][i] == 'a')){
                indices.push(true);
            } else if (tog_z.active && (source.data['scope_type'][i] == 'z')) {
                indices.push(true);
            } else {
                indices.push(false);
            }
        }
        console.log(indices);
        return indices;
    ''')
    view = CDSView(source=source,
                   filters=[filter_verified, filter_junk, filter_scope])

    p = figure(
        tools=['pan,box_zoom,wheel_zoom,box_select,lasso_select,reset,tap'],
        active_scroll='wheel_zoom')

    segs = p.segment(y0='first_frame',
                     y1='last_frame',
                     x0='first_cbd',
                     x1='last_cbd',
                     color=app.config["COLOR_GRAY"],
                     source=source,
                     view=view)
    scat_first = p.scatter('first_cbd',
                           'first_frame',
                           color='Color by Verified',
                           source=source,
                           view=view,
                           nonselection_fill_color=app.config["COLOR_GRAY"])
    scat_last = p.scatter('last_cbd',
                          'last_frame',
                          color='Color by Verified',
                          source=source,
                          view=view,
                          nonselection_fill_color=app.config["COLOR_GRAY"])

    p.add_tools(
        HoverTool(renderers=[segs],
                  tooltips=[("Reel", "@reel"), ("Scope", "@scope_type"),
                            ("Verified", "@is_verified")]))

    p.xaxis.axis_label = "CBD"
    p.yaxis.axis_label = "Frame"

    p.sizing_mode = "stretch_both"
    if (width is not None) and (height is not None):
        p.width = width
        p.height = height
    p.title.text = "Film Segments"

    # Select matching code from https://stackoverflow.com/questions/54768576/python-bokeh-customjs-debugging-a-javascript-callback-for-the-taping-tool

    cb_cselect = CustomJS(args=dict(s1=scat_first,
                                    s2=scat_last,
                                    csource=source),
                          code="""
            var selected_color = cb_obj.value;
            s1.glyph.line_color.field = selected_color;
            s1.glyph.fill_color.field = selected_color;
            s2.glyph.line_color.field = selected_color;
            s2.glyph.fill_color.field = selected_color;
            csource.change.emit();
        """)

    color_select = Select(value="Color by Verified",
                          options=[
                              "Color by Verified", "Color by Reel",
                              "Color by Review", "Color by Frequency"
                          ])
    color_select.js_on_change('value', cb_cselect)

    p.toolbar.active_scroll = p.select_one(WheelZoomTool)

    if return_plot:
        return p, column(toggle_verified, toggle_junk, toggle_z, toggle_a,
                         color_select), source
    else:
        layout = row(
            p,
            column(toggle_verified, toggle_junk, toggle_z, toggle_a,
                   color_select))

        script, div = components(layout)
        return f'\n{script}\n\n{div}\n'
Пример #4
0
def plot_chart_bokeh(processed, dataCollection, keys, outputfilename):
    stock = processed['data']

    # Define constants
    W_PLOT = 1000
    H_PLOT = 360
    TOOLS = 'pan,wheel_zoom,reset'

    VBAR_WIDTH = 1 * 12 * 60 * 60 * 1000  # one day in ms
    RED = Category20[7][6]
    GREEN = Category20[5][4]

    BLUE = Category20[3][0]
    BLUE_LIGHT = Category20[3][1]

    ORANGE = Category20[3][2]
    PURPLE = Category20[9][8]
    BROWN = Category20[11][10]

    # ==========================================================================
    # ===================       PLOT CANDLE STICK GRAPH     ====================
    # ==========================================================================
    p1 = figure(plot_width=W_PLOT,
                plot_height=H_PLOT,
                tools=TOOLS,
                toolbar_location='right')

    inc = stock.data['Close'] >= stock.data['Open']
    dec = stock.data['Open'] > stock.data['Close']
    # limit = stock.data['ZC_d2/dt2'] > 10
    # limit = stock.data['ZC_d/dt'] > 0

    # view_inc = CDSView(source=stock, filters=[BooleanFilter(inc), BooleanFilter(limit)])
    # view_dec = CDSView(source=stock, filters=[BooleanFilter(dec), BooleanFilter(limit)])
    view_inc = CDSView(source=stock, filters=[BooleanFilter(inc)])
    view_dec = CDSView(source=stock, filters=[BooleanFilter(dec)])

    # # map dataframe indices to date strings and use as label overrides
    p1.y_range.start = 0.9 * min(stock.data['Low'])
    p1.y_range.end = 1.1 * max(stock.data['High'])
    p1.segment(x0='Date',
               x1='Date',
               y0='Low',
               y1='High',
               color=GREEN,
               source=stock,
               view=view_inc)
    p1.segment(x0='Date',
               x1='Date',
               y0='Low',
               y1='High',
               color=RED,
               source=stock,
               view=view_dec)

    vb1 = p1.vbar(x='Date',
                  width=VBAR_WIDTH,
                  top='Open',
                  bottom='Close',
                  fill_color='forestgreen',
                  fill_alpha=1,
                  line_color='forestgreen',
                  source=stock,
                  view=view_inc,
                  name="price")
    vb2 = p1.vbar(x='Date',
                  width=VBAR_WIDTH,
                  top='Open',
                  bottom='Close',
                  fill_color='orangered',
                  fill_alpha=1,
                  line_color='orangered',
                  source=stock,
                  view=view_dec,
                  name="price")

    # Bollinger band plot
    patch1 = p1.varea(x='Date',
                      y1='lowerband',
                      y2='upperband',
                      source=stock,
                      fill_alpha=0.05,
                      fill_color='dodgerblue')
    patch_line1 = p1.line(x='Date',
                          y='lowerband',
                          source=stock,
                          line_color='blue',
                          line_alpha=0.4)
    patch_line2 = p1.line(x='Date',
                          y='middleband',
                          source=stock,
                          line_color='grey',
                          line_alpha=0.8,
                          line_dash='dotdash')
    patch_line3 = p1.line(x='Date',
                          y='upperband',
                          source=stock,
                          line_color='blue',
                          line_alpha=0.4)

    # ZC Line plot
    zc_7 = p1.line(x='Date',
                   y='ma7',
                   source=stock,
                   line_color='crimson',
                   line_alpha=0.4)
    zc_26 = p1.line(x='Date',
                    y='ma26',
                    source=stock,
                    line_color='darkslateblue',
                    line_alpha=0.4)

    # # Resistance plots
    # r1 = p1.line(x='Date', y='r1', source=stock, line_color='forestgreen', line_dash='dotdash', line_alpha=0.6)
    # r2 = p1.line(x='Date', y='r2', source=stock, line_color='forestgreen', line_dash='dotdash', line_alpha=0.8)
    # r3 = p1.line(x='Date', y='r3', source=stock, line_color='forestgreen', line_dash='dotdash', line_alpha=1.0)

    # # Support plots
    # s1 = p1.line(x='Date', y='s1', source=stock, line_color='crimson', line_dash='dotdash', line_alpha=0.6)
    # s2 = p1.line(x='Date', y='s2', source=stock, line_color='crimson', line_dash='dotdash', line_alpha=0.8)
    # s3 = p1.line(x='Date', y='s3', source=stock, line_color='crimson', line_dash='dotdash', line_alpha=1.0)

    # Extrema plots
    # minima = p1.inverted_triangle(x='Date', y='minima', source=stock, size=5, color="goldenrod", alpha=0.5)
    # maxima = p1.triangle(x='Date', y='maxima', source=stock, size=5, color="teal", alpha=0.5)
    # minima = p1.circle(
    #     x='Date', y='minima', source=stock, size=10,
    #     fill_color="grey", hover_fill_color="firebrick",
    #     fill_alpha=0.2, hover_alpha=0.8, hover_line_color="white")
    # maxima = p1.triangle(
    #     x='Date', y='maxima', source=stock,
    #     size=10, fill_color="grey", fill_alpha=0.2,
    #     hover_fill_color="firebrick", hover_alpha=0.8, hover_line_color="white")

    # Volume plot
    # Setting the second y axis range name and range
    p1.extra_y_ranges = {
        "vol_axis": Range1d(start=0, end=max(stock.data['Volume']) * 4)
    }
    # Adding the second axis to the plot.
    p1.add_layout(LinearAxis(y_range_name="vol_axis", visible=False), 'right')
    vol_inc = p1.vbar(x="Date",
                      top="Volume",
                      bottom=0,
                      width=int(VBAR_WIDTH * 2),
                      fill_color=GREEN,
                      fill_alpha=0.1,
                      line_color=GREEN,
                      line_alpha=0.2,
                      source=stock,
                      view=view_inc,
                      y_range_name="vol_axis")
    vol_dec = p1.vbar(x="Date",
                      top="Volume",
                      bottom=0,
                      width=int(VBAR_WIDTH * 2),
                      fill_color=RED,
                      fill_alpha=0.1,
                      line_color=RED,
                      line_alpha=0.2,
                      source=stock,
                      view=view_dec,
                      y_range_name="vol_axis")

    legend = Legend(items=[
        LegendItem(
            label="All",
            renderers=[
                patch1,
                patch_line1,
                patch_line2,
                patch_line3,
                vol_inc,
                vol_dec,
                zc_7,
                zc_26,
                #    s1, s2, s3,r1, r2, r3,
                #    minima, maxima
            ],
            index=0),
        LegendItem(label="BB",
                   renderers=[patch1, patch_line1, patch_line2, patch_line3],
                   index=1),
        LegendItem(label="Volume", renderers=[vol_inc, vol_dec], index=2),
        LegendItem(label="ZC", renderers=[zc_7, zc_26], index=3),
        LegendItem(label="MA7", renderers=[zc_7], index=4),
        LegendItem(label="MA26", renderers=[zc_26], index=5),
        # LegendItem(label="Support", renderers=[s1, s2, s3], index=6),
        # LegendItem(label="Resistance", renderers=[r1, r2, r3], index=7),
        # LegendItem(label="Extrema", renderers=[minima, maxima], index=8)
    ])
    p1.add_layout(legend)
    p1.legend.location = "top_left"
    p1.legend.border_line_alpha = 0
    p1.legend.background_fill_alpha = 0
    p1.legend.click_policy = "hide"
    p1.legend.orientation = "horizontal"
    # p1.add_layout(Title(text="Stock price", align="left"), "left")

    p1.yaxis.axis_label = 'Stock price'
    p1.yaxis.formatter = NumeralTickFormatter(format='0.00')
    p1.x_range.range_padding = 0.05
    p1.xaxis.ticker.desired_num_ticks = 40
    p1.xaxis.major_label_orientation = 3.14 / 4
    p1.xaxis.visible = False
    p1.xgrid.grid_line_color = None
    p1.ygrid.grid_line_color = None

    # Select specific tool for the plot
    p1.add_tools(
        HoverTool(
            tooltips=[("Datetime", "@Date{%Y-%m-%d}"),
                      ("Open", "@Open{0,0.00}"), ("Close", "@Close{0,0.00}"),
                      ("Volume", "@Volume{(0.00 a)}")],
            formatters={"@Date": 'datetime'},

            # display a tooltip whenever the cursor is vertically in line with a glyph
            mode='vline',
            renderers=[vb1, vb2]))

    # ==========================================================================
    # ===================      PLOT STOCH / RSI GRAPH          =================
    # ==========================================================================
    p2 = figure(plot_width=W_PLOT,
                plot_height=int(H_PLOT / 4),
                tools=TOOLS,
                toolbar_location='above',
                x_range=p1.x_range,
                x_axis_type='datetime')  # , y_range=(-20, 120)

    stoch_k = p2.line(x='Date',
                      y='slowk',
                      source=stock,
                      line_color='royalblue',
                      alpha=0.8,
                      muted_alpha=0.2)
    stoch_d = p2.line(x='Date',
                      y='slowd',
                      source=stock,
                      line_color='tomato',
                      alpha=0.8,
                      muted_alpha=0.2)
    rsi = p2.line(x='Date',
                  y='rsi',
                  source=stock,
                  line_color='gray',
                  alpha=0.8,
                  muted_alpha=0.2)
    mid_box = BoxAnnotation(bottom=20,
                            top=80,
                            fill_alpha=0.2,
                            fill_color='palegreen',
                            line_color='lightcoral',
                            line_alpha=0.4,
                            line_dash='dashed')
    # candle = p2.line(x='Date', y='candle', source=stock, line_color='royalblue', alpha=0.8, muted_alpha=0.2)
    # mid_box = BoxAnnotation(bottom=-300, top=300, fill_alpha=0.2, fill_color='palegreen', line_color='lightcoral', line_alpha=0.4, line_dash='dashed')
    legend = Legend(items=[
        LegendItem(label="Stoch", renderers=[stoch_k, stoch_d], index=0),
        LegendItem(label="RSI", renderers=[rsi], index=1)
        # LegendItem(label="Candle", renderers=[candle], index=1)
    ])
    p2.add_layout(legend)
    p2.add_layout(mid_box)
    # p2.add_layout(lower)
    zero = Span(location=0,
                dimension='width',
                line_color='seagreen',
                line_dash='solid',
                line_width=0.8)
    p2.add_layout(zero)
    p2.yaxis.axis_label = 'Stochastic / RSI'
    p2.x_range.range_padding = 0.05
    # p2.toolbar.autohide = True
    p2.xaxis.visible = False
    p2.legend.location = "top_left"
    p2.legend.border_line_alpha = 0
    p2.legend.background_fill_alpha = 0
    p2.legend.click_policy = "mute"
    p2.xgrid.grid_line_color = None
    p2.ygrid.grid_line_color = None

    # ==========================================================================
    # ===================                 Plot MACD         ====================
    # ==========================================================================
    y_limit = abs(max(stock.data['macd_hist'], key=abs))
    y2_limit = abs(max(stock.data['macd_d/dt'], key=abs))
    p3 = figure(plot_width=W_PLOT,
                plot_height=int(H_PLOT / 2.5),
                tools=TOOLS,
                toolbar_location='above',
                x_range=p1.x_range,
                x_axis_type='datetime',
                y_range=(-y_limit, y_limit))
    mapper = LinearColorMapper(palette=Viridis256)
    macd_line = p3.line(x='Date',
                        y='macd_hist',
                        source=stock,
                        line_color='darkgreen',
                        alpha=0.8,
                        muted_alpha=0.2)
    # macd_hist = p3.vbar_stack(['macd'], x='Date', source=stock, width=int(VBAR_WIDTH * 2), fill_color={'field':'macd', 'transform': mapper})

    mid_box = BoxAnnotation(bottom=-0.5,
                            top=0.5,
                            fill_alpha=0.2,
                            fill_color='blanchedalmond',
                            line_color='grey',
                            line_alpha=0.4,
                            line_dash='dashed')
    zero = Span(location=0,
                dimension='width',
                line_color='seagreen',
                line_dash='solid',
                line_width=0.8)
    p3.add_layout(zero)
    p3.add_layout(mid_box)

    # Setting the second y axis range name and range
    p3.extra_y_ranges = {
        "extra_y_axis": Range1d(start=-y2_limit, end=y2_limit)
    }
    # Adding the second axis to the plot.
    p3.add_layout(LinearAxis(y_range_name="extra_y_axis"), 'right')
    macd_v = p3.line(x='Date',
                     y='macd_d/dt',
                     source=stock,
                     line_color='dodgerblue',
                     line_dash='solid',
                     alpha=0.8,
                     muted_alpha=0.2,
                     y_range_name="extra_y_axis")
    macd_acc = p3.line(x='Date',
                       y='macd_d2/dt2',
                       source=stock,
                       line_color='tomato',
                       line_dash='dotdash',
                       alpha=0.8,
                       muted_alpha=0.2,
                       y_range_name="extra_y_axis")

    legend = Legend(items=[
        LegendItem(label="MACD", renderers=[macd_line], index=0),
        LegendItem(label="MACD-v", renderers=[macd_v], index=1),
        LegendItem(label="MACD-a", renderers=[macd_acc], index=2)
    ])
    p3.add_layout(legend)
    p3.legend.location = "top_left"
    p3.legend.border_line_alpha = 0
    p3.legend.background_fill_alpha = 0
    p3.legend.click_policy = "mute"
    p3.legend.orientation = "horizontal"
    # p3.add_layout(Title(text="MACD", align="center"), "left")
    p3.yaxis.axis_label = 'MACD'
    p3.x_range.range_padding = 0.05
    p3.xaxis.visible = False
    p3.xaxis.ticker.desired_num_ticks = 40
    p3.xaxis.major_label_orientation = 3.14 / 4
    p3.toolbar.autohide = True
    p3.xgrid.grid_line_color = None
    p3.ygrid.grid_line_color = None

    # ==========================================================================
    # ===================         Plot ZC        ====================
    # ==========================================================================
    y_limit = abs(max(stock.data['ZC'], key=abs))
    y2_limit = abs(max(stock.data['ZC_d/dt'], key=abs))
    # y_limit = abs(max(stock.data['slowk'], key=abs))
    # y2_limit = abs(max(stock.data['slowk_d/dt'], key=abs))
    p4 = figure(plot_width=W_PLOT,
                plot_height=int(H_PLOT / 3),
                tools=TOOLS,
                toolbar_location='above',
                x_range=p1.x_range,
                x_axis_type='datetime',
                y_range=(-y_limit, y_limit))

    p4.xaxis.formatter = DatetimeTickFormatter(
        hours=["%d.%m.%y"],
        days=["%d.%m.%y"],
        months=["%d.%m.%y"],
        years=["%d.%m.%y"],
    )
    # macd_v = p4.line(x='Date', y='macd_d/dt', source=stock, line_color='royalblue', alpha=0.8, muted_alpha=0.2)
    # macd_acc = p4.line(x='Date', y='macd_d2/dt2', source=stock, line_color='tomato', alpha=0.8, muted_alpha=0.2)
    # ad = p4.line(x='Date', y='ck_AD', source=stock, line_color='royalblue', alpha=0.8, muted_alpha=0.2)
    # adosc = p4.line(x='Date', y='ck_ADOSC', source=stock, line_color='tomato', alpha=0.8, muted_alpha=0.2)
    # obv = p4.line(x='Date', y='OBV', source=stock, line_color='darkgreen', alpha=0.8, muted_alpha=0.2)

    # Setting the second y axis range name and range
    p4.extra_y_ranges = {
        "extra_y_axis": Range1d(start=-y2_limit, end=y2_limit)
    }
    # Adding the second axis to the plot.
    p4.add_layout(LinearAxis(y_range_name="extra_y_axis"), 'right')

    zc = p4.line(x='Date',
                 y='ZC',
                 source=stock,
                 line_color='darkgreen',
                 alpha=0.8,
                 muted_alpha=0.2)
    zc_v = p4.line(x='Date',
                   y='ZC_d/dt',
                   source=stock,
                   line_color='dodgerblue',
                   line_dash='dotdash',
                   alpha=0.8,
                   muted_alpha=0.2,
                   y_range_name="extra_y_axis")
    zc_a = p4.line(x='Date',
                   y='ZC_d2/dt2',
                   source=stock,
                   line_color='tomato',
                   line_dash='dotdash',
                   alpha=0.8,
                   muted_alpha=0.2,
                   y_range_name="extra_y_axis")
    # slowk = p4.line(x='Date', y='slowk', source=stock, line_color='darkgreen', alpha=0.8, muted_alpha=0.2)
    # slowk_v = p4.line(x='Date', y='slowk_d/dt', source=stock, line_color='dodgerblue', line_dash='dotdash', alpha=0.8, muted_alpha=0.2, y_range_name="extra_y_axis")
    # slowk_a = p4.line(x='Date', y='slowk_d2/dt2', source=stock, line_color='tomato', line_dash='dotdash', alpha=0.8, muted_alpha=0.2, y_range_name="extra_y_axis")

    mid_box = BoxAnnotation(bottom=-0.5,
                            top=0.5,
                            fill_alpha=0.2,
                            fill_color='blanchedalmond',
                            line_color='grey',
                            line_alpha=0.4,
                            line_dash='dashed')
    zero = Span(location=0,
                dimension='width',
                line_color='seagreen',
                line_dash='solid',
                line_width=0.8)
    p4.add_layout(zero)
    p4.add_layout(mid_box)
    # p4.yaxis.axis_label = 'MACD v/acc'
    legend = Legend(items=[
        LegendItem(label="ZC", renderers=[zc], index=0),
        LegendItem(label="ZC-v", renderers=[zc_v], index=1),
        LegendItem(label="ZC-a", renderers=[zc_a], index=2),
        # LegendItem(label="slowk", renderers=[slowk], index=0),
        # LegendItem(label="slowk-v", renderers=[slowk_v], index=1),
        # LegendItem(label="slowk-a", renderers=[slowk_a], index=2)
    ])
    p4.add_layout(legend)
    p4.legend.location = "top_left"
    p4.legend.border_line_alpha = 0
    p4.legend.background_fill_alpha = 0
    p4.legend.click_policy = "mute"
    p4.legend.orientation = "horizontal"
    p4.x_range.range_padding = 0.05
    p4.xaxis.ticker.desired_num_ticks = 40
    p4.xaxis.major_label_orientation = 3.14 / 4
    p4.toolbar.autohide = True
    p4.xgrid.grid_line_color = None
    p4.ygrid.grid_line_color = None

    addSpans([p1, p2, p3, p4])

    columns = [
        TableColumn(field="Date",
                    title="Date",
                    formatter=DateFormatter(format='%d.%b')),
        # TableColumn(field="Open", title="Open", formatter=NumberFormatter(format='0.00')),
        # TableColumn(field="Close", title="Close", formatter=NumberFormatter(format='0.00')),
        TableColumn(field="ZC",
                    title="ZC",
                    formatter=NumberFormatter(format='0.000',
                                              text_align='right')),
        TableColumn(field="ZC_d/dt",
                    title="ZC-v",
                    formatter=NumberFormatter(format='0.000',
                                              text_align='right')),
        TableColumn(field="macd_hist",
                    title="MACD",
                    formatter=NumberFormatter(format='0.000',
                                              text_align='right')),
        TableColumn(field="macd_d/dt",
                    title="MACD-v",
                    formatter=NumberFormatter(format='0.000',
                                              text_align='right')),
        # TableColumn(field="macd_d2/dt2", title="MACD-a", formatter=NumberFormatter(format='0.000')),
        TableColumn(field="stoch",
                    title="STOCH",
                    formatter=NumberFormatter(format='0.0',
                                              text_align='right')),
        TableColumn(field="stoch-v",
                    title="STOCH-v",
                    formatter=NumberFormatter(format='0.0',
                                              text_align='right')),
        # TableColumn(field="slowk_d/dt", title="slowk-v", formatter=NumberFormatter(format='0.000')),
        # TableColumn(field="slowk_d2/dt2", title="slowk-a", formatter=NumberFormatter(format='0.000')),
    ]
    data_table = DataTable(source=stock,
                           columns=columns,
                           width=int(W_PLOT / 3),
                           height=int(H_PLOT * 2.2),
                           index_position=None,
                           width_policy='min')

    # ==========================================================================
    # ===================            SELECT WIDGET          ====================
    # ==========================================================================

    callback_select_main = """
        var d0 = s0.data;
        var symbol = cb_obj.value.split(" ")[0]
        var data_all = dataCollection[symbol]
        var data = data_all.data.data;

        /// Iterate over keys in new data and reassign old data with new data
        for (const key of Object.keys(data)) {
            d0[key] = []
            d0[key] = data[key]
        }
        s0.change.emit()

        /// Update y-axes range
        plot.y_range.have_updated_interactively = true
        plot.y_range.start = 0.9 * Math.min(...data['Low'])
        plot.y_range.end = 1.1 * Math.max(...data['High'])
        plot.extra_y_ranges['vol_axis'].have_updated_interactively = true
        plot.extra_y_ranges['vol_axis'].start  = 0
        plot.extra_y_ranges['vol_axis'].end  = Math.max(...data['Volume']) * 4
        """

    callback_select_va = """
        var symbol = cb_obj.value.split(" ")[0]
        var data_all = dataCollection[symbol]
        var data = data_all.data.data;
        var y_limit = Math.max.apply(null, data[param_main].map(Math.abs));
        var y_extra_limit = Math.max.apply(null, data[param_extra].map(Math.abs));
        /// Update y-axes range
        plot.y_range.have_updated_interactively = true
        plot.y_range.start = -y_limit
        plot.y_range.end = y_limit
        plot.extra_y_ranges['extra_y_axis'].have_updated_interactively = true
        plot.extra_y_ranges['extra_y_axis'].start  = -y_extra_limit
        plot.extra_y_ranges['extra_y_axis'].end  = y_extra_limit
        """
    selecthandler_main = CustomJS(args={
        's0': stock,
        'dataCollection': dataCollection,
        'plot': p1
    },
                                  code=callback_select_main)
    selecthandler_p3 = CustomJS(args={
        'dataCollection': dataCollection,
        'plot': p3,
        'param_main': 'macd_hist',
        'param_extra': 'macd_d/dt'
    },
                                code=callback_select_va)
    selecthandler_p4 = CustomJS(args={
        'dataCollection': dataCollection,
        'plot': p4,
        'param_main': 'ZC',
        'param_extra': 'ZC_d/dt'
    },
                                code=callback_select_va)
    # selecthandler_p4 = CustomJS(args={'dataCollection':dataCollection, 'plot':p4, 'param_main': 'slowk', 'param_extra': 'slowk_d/dt'}, code = callback_select_va)
    select = Select(title="Select:", value=keys[0], options=keys)
    select.js_on_change('value', selecthandler_main)
    select.js_on_change('value', selecthandler_p3)
    select.js_on_change('value', selecthandler_p4)

    # [cleanDate(x, stock.data) for x in [p1, p2, p3, p4]]
    # show the results
    gp1 = gridplot([select, data_table],
                   ncols=1,
                   plot_width=150,
                   toolbar_options=dict(autohide=True))
    gp2 = gridplot([p1, p2, p3, p4],
                   ncols=1,
                   sizing_mode='scale_width',
                   toolbar_location='right')

    output_file(outputfilename + '.html')
    show(row(gp1, gp2))
    # show(gp2)
    return True
Пример #5
0
    def create_figure(cut_off, df, output_backend):
        columns = sorted(df.columns[2:])

        #Initialize variables for data input
        xs = df[x.value].values
        ys = df[y.value].values
        geneid = df['AlternateID'].values
        desc = df['Annotation'].values
        x_title = x.value.lower()
        y_title = y.value.lower()

        #create a new column in df named seq storing protein sequences
        result = {}
        for i in geneid:
            if i in record_dict.keys():
                result[i] = str(record_dict[i].seq)
            else:
                result[i] = str('*')
        df['seq'] = result.values()
        seq = df['seq'].values

        data = {
            'x_values':
            xs,
            'y_values':
            ys,
            'fold_change': [(-x / y) if (x > y and y != 0) else (y / x) if
                            (y >= x and x != 0) else 'NaN'
                            for x, y in zip(xs, ys)],
            'GeneID':
            geneid,
            'Annotation':
            desc,
            'seq':
            seq
        }

        mysource = ColumnDataSource(data=data)

        #use CDSView function to determine a subset of significant genes for visualization
        significant_xy_view = CDSView(
            source=mysource,
            filters=[
                BooleanFilter([
                    True if
                    ((geneX > 0 and geneY > 0 and
                      (abs(geneX / geneY) > cut_off)) or
                     (geneX > 0 and geneY > 0 and abs(geneY / geneX) > cut_off)
                     and (geneX + geneY) > 10) else False
                    for geneX, geneY in zip(mysource.data['x_values'],
                                            mysource.data['y_values'])
                ])
            ])

        # create a plot and style its properties
        kw = dict()
        kw['title'] = "%s vs %s" % (x_title, y_title)

        #make a plot
        p = figure(plot_height=500,
                   plot_width=700,
                   output_backend=output_backend,
                   tools='pan,box_zoom,wheel_zoom,reset,save,tap',
                   **kw)

        #make sure WheelZoomTool is activated by default
        p.toolbar.active_scroll = p.select_one(WheelZoomTool)
        p.xaxis.axis_label = x_title
        p.yaxis.axis_label = y_title
        p.yaxis.axis_label_text_font_size = '10pt'
        p.xaxis.axis_label_text_font_size = '10pt'
        p.yaxis.major_label_text_font_size = '10pt'
        p.xaxis.major_label_text_font_size = '10pt'
        p.title.text_font_size = '12pt'

        common_circle_kwargs = {
            'x': 'x_values',
            'y': 'y_values',
            'source': mysource,
            'hover_color': 'black'
        }

        p.circle(**common_circle_kwargs,
                 color="skyblue",
                 alpha=0.7,
                 size=9,
                 line_color="white")

        p.circle(**common_circle_kwargs,
                 view=significant_xy_view,
                 color="red",
                 muted_alpha=0.1,
                 legend_label='sig. genes',
                 size=9,
                 line_color="black")

        # Highlighting of genes using a substring in the gene annotation, if it is provided in the Textfield
        if desc_sel.value != "":
            selected = df[df.Annotation.str.contains(desc_sel.value,
                                                     case=False) == True]
            p.circle(x=selected[x.value].values,
                     y=selected[y.value].values,
                     color="yellow",
                     alpha=1.0,
                     muted_alpha=0.1,
                     legend_label='sel. genes',
                     size=8,
                     line_color="black")

        # Set autohide to true to only show the toolbar when mouse is over plot
        p.toolbar.autohide = True

        p.legend.title = 'Click to hide'
        p.legend.location = "bottom_right"
        p.legend.border_line_width = 1
        p.legend.border_line_color = "black"
        p.legend.border_line_alpha = 0.5

        # use the "seq" column of mysource to complete the URL
        # e.g. if the glyph at index 1 is selected, then @seq
        # will be replaced with mysource.data['seq'][1]
        url = "http://papers.genomics.lbl.gov/cgi-bin/litSearch.cgi?query=@seq&Search=Search"
        taptool = p.select(type=TapTool)
        taptool.callback = OpenURL(url=url)

        # Format the tooltip
        tooltips = [('GeneID', '@GeneID'), ('Annotation', '@Annotation{safe}'),
                    ('fold change', '@fold_change'),
                    ('FPKM (%s)' % (x_title), '@x_values'),
                    ('FPKM (%s)' % (y_title), '@y_values')]

        # Configure a renderer to be used upon hover
        hover_glyph = p.circle(**common_circle_kwargs,
                               size=15,
                               alpha=0,
                               hover_fill_color='black',
                               hover_alpha=0.5)

        # Add the custom HoverTool to the figure
        p.add_tools(HoverTool(tooltips=tooltips, renderers=[hover_glyph]))

        # Add the custom CrosshairTool to the figure
        p.add_tools(CrosshairTool(line_width=1))

        # Add interactivity to the legend
        p.legend.click_policy = "hide"

        return p
Пример #6
0
def map_plot(data, features_titles, output_choice_selection):
    full_source = ColumnDataSource(data)  # a CDS version of the data obtained

    # a CDS version of the data to plot, modifiable by geo dropdowns, to be produced in the callback
    num_instances = len(data)

    # Split the columns with the values to plot to build their marks and title
    geo_columns = [
        'practice_code', 'practice', 'ccg', 'region', 'sub_region',
        'longitudemerc', 'latitudemerc'
    ]
    value_columns = [h for h in data.columns if h not in geo_columns]

    # Assert gender-age as the second value (to be marked by size)
    if value_columns[0] in ['gender', 'age_groups', 'gender_age_groups']:
        value_columns = list(reversed(value_columns))

    first_value = value_columns[0]
    features_marks = {first_value: 'Color'}
    hover_first_value = '@{fv}'.format(fv=first_value)

    # Normalized size values for the second feature if such exists
    if len(value_columns) == 2:
        second_value = value_columns[1]
        sv_column = np.array(data[second_value])
        svinterp = np.interp(sv_column, (sv_column.min(), sv_column.max()),
                             (0, 2000))  #was 10 for size
        if second_value == 'deprivation':
            svinterp = max(svinterp) - svinterp
        norm_header = second_value + '_norm'
        data[norm_header] = svinterp
        features_marks[second_value] = 'Size'

    source = ColumnDataSource(data)
    filter = IndexFilter(indices=list(data.index))
    view = CDSView(source=source, filters=[filter])
    plot = figure(x_axis_type="mercator",
                  y_axis_type="mercator",
                  plot_height=700,
                  plot_width=700)
    plot.title.text_color = 'purple'
    tooltips = [('Practice', '@practice'), ('CCG', '@ccg'),
                (first_value.capitalize(), hover_first_value)]

    # Title
    title_parts = []
    for feature, title in features_titles.items():
        title_part = '  {m}: {t}'.format(m=features_marks[feature], t=title)
        title_parts.append(title_part)

    title_parts = list(reversed(title_parts))
    for title_part in title_parts:
        plot.add_layout(
            Title(text=title_part, text_font_size="10pt", text_color='purple'),
            'above')

    # Color mapper
    palette = list(reversed(brewer['YlOrRd'][9]))
    if first_value == 'deprivation':
        low_boundary, high_boundary = max(source.data[first_value]), min(
            source.data[first_value])
    else:
        high_boundary, low_boundary = max(source.data[first_value]), min(
            source.data[first_value])

    mapper = linear_cmap(field_name=first_value, palette=palette,\
    low=low_boundary, high=high_boundary) #Spectral6

    # add map tiles
    map_tile = get_provider(Vendors.CARTODBPOSITRON)
    plot.add_tile(map_tile)

    if len(value_columns) == 2:
        hover_second_value = '@{sv}'.format(sv=second_value)
        tooltips.append((second_value.capitalize(), hover_second_value))

        plot.circle(source=source, x='latitudemerc',y='longitudemerc',\
        hover_color='red', color=mapper,radius = norm_header, alpha=0.2,\
        view = view)
    else:
        plot.circle(source=source, view=view, x='latitudemerc',y='longitudemerc',\
        hover_color='red', color=mapper)

    hover = HoverTool(tooltips=tooltips)
    color_bar = ColorBar(color_mapper=mapper['transform'],
                         width=8,
                         location=(0, 0))
    plot.add_layout(color_bar, 'right')
    plot.add_tools(hover)

    # Plot widgets selection callback
    callback = CustomJS(args=dict(source=source, filter=filter),
                        code='''
      var indices = []
      var selected_value = cb_obj.value
      if (selected_value=='All') {
        indices = source.index
        console.log ('all ccgs selected')
      } else {
      console.log('The selected area is ' + selected_value)
      for (var i = 0; i < source.get_length(); i++) {
        // console.log(i, source.data['ccg'][i], cb_obj.value)
        if ((source.data['ccg'][i] == selected_value) || (source.data['region'][i] == selected_value)\
        ||  (source.data['sub_region'][i] == selected_value)) {
          indices.push(i)
             }
            }
          }
      filter.indices = indices
      source.change.emit()
    ''')

    select_ccg = Select(title='CCG', value=ccgs[0], options=ccgs, width=120)
    select_ccg.js_on_change('value', callback)
    select_region = Select(title='Region',
                           value=regions[0],
                           options=regions,
                           width=120)
    select_region.js_on_change('value', callback)
    select_sub_region = Select(title='Sub-Region',
                               value=sub_regions[0],
                               options=sub_regions,
                               width=120)
    select_sub_region.js_on_change('value', callback)
    view = CDSView(source=source, filters=[filter])

    if output_choice_selection == 'Notebook':
        output_notebook()
    elif output_choice_selection == 'HTML File':
        output_file('plot.html')
    show(row(column(select_region, select_sub_region, select_ccg), plot))
Пример #7
0
    def plot_bokeh(self,
                   plot_name=None,
                   show_plot=False,
                   barplot=True,
                   chng=True):
        """
        Plot OOB-scores as bar- or linechart in bokeh.

        Parameters
        ----------
        plot_name: str
            path where to store the plot, None to not save it
        show_plot: bool
            whether or not to open plot in standard browser
        barplot: bool
            plot OOB as barchart
        chng: bool
            plot OOB as linechart

        Returns
        -------
        layout: bokeh.models.Row
            bokeh plot (can be used in notebook or comparted with components)
        """
        # Get all relevant data-points
        params = list(self.evaluated_parameter_importance.keys())
        p_names_short = shorten_unique(params)
        errors = list(self.evaluated_parameter_importance.values())
        max_to_plot = min(len(errors), self.MAX_PARAMS_TO_PLOT)
        plot_indices = sorted(range(len(errors)),
                              key=lambda x: errors[x],
                              reverse=True)[:max_to_plot]

        # Customizing plot-style
        bar_width = 25

        # Create ColumnDataSource for both plots
        source = ColumnDataSource(data=dict(
            parameter_names_short=p_names_short,
            parameter_names=params,
            parameter_importance=errors,
        ))
        plots = []

        view = CDSView(source=source, filters=[IndexFilter(plot_indices)])
        tooltips = [
            ("Parameter", "@parameter_names"),
            ("Importance", "@parameter_importance"),
        ]
        if barplot:
            p = figure(x_range=p_names_short,
                       plot_height=350,
                       plot_width=100 + max_to_plot * bar_width,
                       toolbar_location=None,
                       tools="hover",
                       tooltips=tooltips)

            p.vbar(x='parameter_names_short',
                   top='parameter_importance',
                   width=0.9,
                   source=source,
                   view=view)
            for value in [
                    self.IMPORTANCE_THRESHOLD, -self.IMPORTANCE_THRESHOLD
            ]:
                p.add_layout(
                    Span(location=value,
                         dimension='width',
                         line_color='red',
                         line_dash='dashed'))

            plots.append(p)

        if chng:
            p = figure(x_range=p_names_short,
                       plot_height=350,
                       plot_width=100 + max_to_plot * bar_width,
                       toolbar_location=None,
                       tools="hover",
                       tooltips=tooltips)

            p.line(x='parameter_names_short',
                   y='parameter_importance',
                   source=source,
                   view=view)

            plots.append(p)

        # Common styling:
        for p in plots:
            p.xaxis.major_label_orientation = 1.3
            p.xaxis.major_label_text_font_size = "14pt"
            p.yaxis.formatter = BasicTickFormatter(use_scientific=False)
            p.yaxis.axis_label = 'CV-RMSE' if self.cv else 'OOB'

        layout = Row(*plots)

        # Save and show...
        save_and_show(plot_name, show_plot, layout)

        return layout
Пример #8
0
            ]  # columns with object/categorical variables
countable = [
    col for col in discrete if len(df[col].unique()) <= COUNTABLE_LIMIT
]  # columns to be used for color options
continuous = [col for col in columns if col not in discrete
              ]  # columns with continueous variables (for axis options)

# get rid of null error
for key in df:
    df[key] = ['NaN' if pd.isnull(value) else value for value in df[key]]

# set Bokeh ColumnDataSource to dataframe values
source = ColumnDataSource(df)

# init table_source to an unfiltered CDSView of source
table_source = CDSView(source=source)

# intitialise dropdown selection widget variables
x_axis = X_INIT
y_axis = Y_INIT
color_cat = COLOR_INIT
toggle_val = TOGGLE_INIT

# init Bokeh server document
doc = curdoc()

# create initial data table
data_table = create_table()
data_table.width = 1500

# create x-axis dropdown widget with continuous var columns
Пример #9
0
# General API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------

# TODO: ideally, the list of arguments should be received directly from
# GlyphRenderer, but such case requires a system that would be able to generate
# acceptable values for parameters
_renderer_args_values = dict(
    name=[None, "", "test name"],
    x_range_name=[None, "", "x range"],
    y_range_name=[None, "", "y range"],
    level=[None, "overlay"],
    view=[None, CDSView(source=ColumnDataSource())],
    visible=[None, False, True],
    muted=[None, False, True],
)


@pytest.mark.parametrize('arg,values', [(arg, _renderer_args_values[arg])
                                        for arg in RENDERER_ARGS])
def test__glyph_receives_renderer_arg(arg, values) -> None:
    for value in values:
        with mock.patch('bokeh.plotting._renderer.GlyphRenderer',
                        autospec=True) as gr_mock:

            def foo(**kw):
                pass
Пример #10
0
                                       effector_conc=c_range,
                                       ka=139,
                                       ki=0.53,
                                       ep_ai=4.5,
                                       n_sites=2)
ref_fc = ref_arch.fold_change()
ref_bohr = ref_arch.bohr_parameter()
ref_delta_bohr = ref_bohr - ref_bohr
# Define the source
source = ColumnDataSource(data=dict(c=c_range,
                                    ref_fc=ref_fc,
                                    mut_fc=ref_fc,
                                    mut_bohr=ref_bohr,
                                    mut_delta_bohr=ref_delta_bohr,
                                    ref_bohr=ref_bohr))
view = CDSView(source=source, filters=[IndexFilter(subsamp)])

# Instantiate the figure canvas
p_fc = bokeh.plotting.figure(width=400,
                             height=300,
                             x_axis_type='log',
                             x_axis_label='IPTG [µM]',
                             y_axis_label='fold-change',
                             x_range=[1E-2, 1E5],
                             y_range=[-0.1, 1.1],
                             title='Induction Profile')
p_bohr = bokeh.plotting.figure(width=425,
                               height=300,
                               x_axis_label='free energy [kT]',
                               y_axis_label='fold-change',
                               x_range=[-15, 15],
Пример #11
0
def plot_pair(
    ax,
    infdata_group,
    numvars,
    figsize,
    textsize,
    kind,
    plot_kwargs,
    contour,
    fill_last,
    divergences,
    diverging_mask,
    flat_var_names,
    backend_kwargs,
    show,
):
    """Bokeh pair plot."""
    if backend_kwargs is None:
        backend_kwargs = {}

    backend_kwargs = {
        **backend_kwarg_defaults(
            ("tools", "plot.bokeh.tools"),
            ("output_backend", "plot.bokeh.output_backend"),
            ("dpi", "plot.bokeh.figure.dpi"),
        ),
        **backend_kwargs,
    }
    dpi = backend_kwargs.pop("dpi")
    if numvars == 2:
        (figsize, _, _, _, _, _) = _scale_fig_size(figsize, textsize,
                                                   numvars - 1, numvars - 1)

        source_dict = dict(
            zip(flat_var_names, [list(post) for post in infdata_group]))

        if divergences:
            divergenve_name = "divergences_{}".format(str(uuid4()))
            source_dict[divergenve_name] = (
                np.array(diverging_mask).astype(bool).astype(int).astype(str))

        source = ColumnDataSource(data=source_dict)

        if divergences:
            source_nondiv = CDSView(
                source=source,
                filters=[GroupFilter(column_name=divergenve_name, group="0")])
            source_div = CDSView(
                source=source,
                filters=[GroupFilter(column_name=divergenve_name, group="1")])

        if ax is None:
            ax = bkp.figure(width=int(figsize[0] * dpi),
                            height=int(figsize[1] * dpi),
                            **backend_kwargs)

        if kind == "scatter":
            if divergences:
                ax.circle(
                    flat_var_names[0],
                    flat_var_names[1],
                    source=source,
                    view=source_nondiv,
                    legend_label="non-divergent",
                )
            else:
                ax.circle(flat_var_names[0], flat_var_names[1], source=source)
        elif kind == "kde":
            plot_kde(
                infdata_group[0],
                infdata_group[1],
                contour=contour,
                fill_last=fill_last,
                ax=ax,
                backend="bokeh",
                backend_kwargs={},
                show=False,
            )
        else:
            ax.hexbin(infdata_group[0], infdata_group[1], size=0.5)
            ax.grid.visible = False

        if divergences:
            ax.circle(
                flat_var_names[0],
                flat_var_names[1],
                line_color="black",
                fill_color="orange",
                line_width=1,
                size=6,
                source=source,
                view=source_div,
                legend_label="divergent",
            )
            ax.legend.click_policy = "hide"

        ax.xaxis.axis_label = flat_var_names[0]
        ax.yaxis.axis_label = flat_var_names[1]

        if backend_show(show):
            bkp.show(ax)

    else:
        max_plots = (numvars**2 if rcParams["plot.max_subplots"] is None else
                     rcParams["plot.max_subplots"])
        vars_to_plot = np.sum(np.arange(numvars).cumsum() < max_plots)
        if vars_to_plot < numvars:
            warnings.warn(
                "rcParams['plot.max_subplots'] ({max_plots}) is smaller than the number "
                "of resulting pair plots with these variables, generating only a "
                "{side}x{side} grid".format(max_plots=max_plots,
                                            side=vars_to_plot),
                UserWarning,
            )
            numvars = vars_to_plot

        (figsize, _, _, _, _, _) = _scale_fig_size(figsize, textsize,
                                                   numvars - 2, numvars - 2)

        if ax is None:
            ax = []
            for row in range(numvars - 1):
                row_ax = []
                for col in range(numvars - 1):
                    if row < col:
                        row_ax.append(None)
                    else:
                        ax_ = bkp.figure(
                            width=int(figsize[0] / (numvars - 1) * dpi),
                            height=int(figsize[1] / (numvars - 1) * dpi),
                            **backend_kwargs)
                        row_ax.append(ax_)
                ax.append(row_ax)
            ax = np.array(ax)

        tmp_flat_var_names = None
        if len(flat_var_names) == len(list(set(flat_var_names))):
            source_dict = dict(
                zip(flat_var_names, [list(post) for post in infdata_group]))
        else:
            tmp_flat_var_names = [
                "{}__{}".format(name, str(uuid4())) for name in flat_var_names
            ]
            source_dict = dict(
                zip(tmp_flat_var_names,
                    [list(post) for post in infdata_group]))
        if divergences:
            divergenve_name = "divergences_{}".format(str(uuid4()))
            source_dict[divergenve_name] = (
                np.array(diverging_mask).astype(bool).astype(int).astype(str))

        source = ColumnDataSource(data=source_dict)

        if divergences:
            source_nondiv = CDSView(
                source=source,
                filters=[GroupFilter(column_name=divergenve_name, group="0")])
            source_div = CDSView(
                source=source,
                filters=[GroupFilter(column_name=divergenve_name, group="1")])

        for i in range(0, numvars - 1):
            var1 = flat_var_names[
                i] if tmp_flat_var_names is None else tmp_flat_var_names[i]

            for j in range(0, numvars - 1):
                if j < i:
                    continue

                var2 = (flat_var_names[j + 1] if tmp_flat_var_names is None
                        else tmp_flat_var_names[j + 1])

                if kind == "scatter":
                    if divergences:
                        ax[j, i].circle(var1,
                                        var2,
                                        source=source,
                                        view=source_nondiv)
                    else:
                        ax[j, i].circle(var1, var2, source=source)

                elif kind == "kde":
                    var1_kde = infdata_group[i]
                    var2_kde = infdata_group[j + 1]
                    plot_kde(var1_kde,
                             var2_kde,
                             contour=contour,
                             fill_last=fill_last,
                             ax=ax[j, i],
                             backend="bokeh",
                             backend_kwargs={},
                             show=False,
                             **plot_kwargs)

                else:
                    var1_hexbin = infdata_group[i]
                    var2_hexbin = infdata_group[j + 1]
                    ax[j, i].grid.visible = False
                    ax[j, i].hexbin(var1_hexbin, var2_hexbin, size=0.5)

                if divergences:
                    ax[j, i].circle(
                        var1,
                        var2,
                        line_color="black",
                        fill_color="orange",
                        line_width=1,
                        size=10,
                        source=source,
                        view=source_div,
                    )

                ax[j, i].xaxis.axis_label = flat_var_names[i]
                ax[j, i].yaxis.axis_label = flat_var_names[j + 1]

        if backend_show(show):
            grid = gridplot(ax.tolist(), toolbar_location="above")
            bkp.show(grid)

    return ax
Пример #12
0
print(data.head())
print(len(pd.unique(data['name'])))

colormap = {'R': 'red', 'L': 'green', 'B' : 'blue'}
colors = [colormap[x] for x in data['handedness']]

source = ColumnDataSource(data)

tools = ["box_select", "hover", "pan", "box_zoom", "reset"]
p_all = figure(tools = tools, title = 'Batting Average vs Home Runs of all players', height = 200)
p_all.xaxis.axis_label = 'Average'
p_all.yaxis.axis_label = 'Home Runs'
p_all.circle(x="avg", y="HR", color = colors, hover_color="red", source = source)


view1 = CDSView(source=source, filters=[GroupFilter(column_name='handedness', group='R')])
p_R = figure(tools = tools, title = 'Batting Average vs Home Runs of right handed players', height = 200)
p_R.xaxis.axis_label = 'Average'
p_R.yaxis.axis_label = 'Home Runs'
p_R.circle(x="avg", y="HR", color = 'red', hover_color="yellow", view=view1, source = source)


view2 = CDSView(source=source, filters=[GroupFilter(column_name='handedness', group='L')])
p_L = figure(tools = tools, title = 'Batting Average vs Home Runs of left handed players', height = 200)
p_L.xaxis.axis_label = 'Average'
p_L.yaxis.axis_label = 'Home Runs'
p_L.circle(x="avg", y="HR", color = 'green', hover_color="yellow", view=view2, source = source)

view3 = CDSView(source=source, filters=[GroupFilter(column_name='handedness', group='B')])
p_B = figure(tools = tools, title = 'Batting Average vs Home Runs of both handed players', height = 200)
p_B.xaxis.axis_label = 'Average'
Пример #13
0
    def plot_recension_all(self, fs_dict, gs_dict, df_dict):
        """This function returns the map based on the entered values as follows:
            fs_dic ~ dictionary of  coastal localities in Omega  -->dict
            gs_dict ~dictionary of  coastal localities in Xi  -->dict
            df_dic ~ dictionary of all localities -->dict
            """

        tools = [
            "hover", "crosshair", "box_select", "box_zoom", "wheel_zoom",
            "reset"
        ]
        TOOLTIPS = [("index", "$index"), ("(x,y)", "($x, $y)")]
        p = figure(title=self.select_recension,
                   width=1000,
                   height=800,
                   x_range=(1.5, 22),
                   y_range=(35.5, 47),
                   tools=tools,
                   tooltips=TOOLTIPS)
        for i in self.fs_dict.values():
            p.line(i[:, 0],
                   i[:, 1],
                   color="dodgerblue",
                   legend="Coasts and boundaries (Omega)",
                   line_width=1.5)
        co = "dfTemp"
        Locality = {
            "x": list(self.df_dict["dfTemp"]['longitude']),
            "y": list(self.df_dict["dfTemp"]['latitude'])
        }
        source = ColumnDataSource(data=Locality)
        view = CDSView(source=source)
        p.circle(x='x',
                 y='y',
                 source=source,
                 view=view,
                 fill_color="dodgerblue",
                 size=6,
                 fill_alpha=.9,
                 line_color="dodgerblue",
                 line_alpha=0.6,
                 legend="Locality (Omega)",
                 muted_alpha=0.2)
        for i in self.gs_dict.values():
            p.line(i[:, 0],
                   i[:, 1],
                   color="red",
                   legend="Coasts and boundaries (Xi)",
                   line_dash="dashdot",
                   line_width=1.5)
        co = 'dfTempX'
        Locality = {
            "x": list(self.df_dict["dfTempX"]['longitude']),
            "y": list(self.df_dict["dfTempX"]['latitude'])
        }
        source = ColumnDataSource(data=Locality)
        view = CDSView(source=source)
        p.circle(x='x',
                 y='y',
                 source=source,
                 view=view,
                 fill_color="crimson",
                 size=6,
                 fill_alpha=.9,
                 line_color="red",
                 line_alpha=0.6,
                 legend="Locality (Xi)",
                 muted_alpha=.2)
        p.legend.click_policy = "mute"
        show(p)
Пример #14
0
    def plot_recension(self, fs_dict, gs_dict, df_dict, select_recension):
        """This function returns the map based on the entered values as follows:
        fs_dic ~ dictionary of  coastal localities in Omega  -->dict
        gs_dict ~dictionary of  coastal localities in Xi  -->dict
        df_dic ~ dictionary of all localities -->dict
        select_recension ~ either 'Omega ' or -'Xi '  -->string
        pay attention to capitalization 
        """

        tools = ["hover", "box_select", "box_zoom", "wheel_zoom", "reset"]
        TOOLTIPS = [("index", "$index"), ("(x,y)", "($x, $y)")]
        p = figure(title=self.select_recension,
                   width=1000,
                   height=800,
                   x_range=(1.5, 22),
                   y_range=(35.5, 47),
                   tooltips=TOOLTIPS,
                   tools=tools)
        p.background_fill_color = "beige"
        p.background_fill_alpha = 0.5
        if select_recension == 'Omega':
            Locality = {
                "x": list(self.df_dict["dfTemp"]['longitude']),
                "y": list(self.df_dict["dfTemp"]['latitude'])
            }
            source = ColumnDataSource(data=Locality)
            view = CDSView(source=source)
            for i in self.fs_dict.values():
                p.line(i[:, 0],
                       i[:, 1],
                       color="black",
                       legend="Coasts and boundaries (Omega)",
                       muted_alpha=0.2)
            co = "dfTemp"
            p.circle(x='x',
                     y='y',
                     source=source,
                     view=view,
                     fill_color="blue",
                     size=6,
                     fill_alpha=.9,
                     line_color="blue",
                     line_alpha=0.6,
                     legend="Locality (Omega) ",
                     muted_alpha=0.2)
        elif select_recension == 'Xi':
            Locality = {
                "x": list(self.df_dict["dfTempX"]['longitude']),
                "y": list(self.df_dict["dfTempX"]['latitude'])
            }
            source = ColumnDataSource(data=Locality)
            view = CDSView(source=source)
            for i in self.gs_dict.values():
                p.line(i[:, 0],
                       i[:, 1],
                       color="black",
                       legend="Coasts and boundaries (Xi) ",
                       muted_alpha=0.2,
                       line_dash="dashdot")
            co = 'dfTempX'
            p.circle(np.array(self.df_dict[co]['longitude']),
                     np.array(self.df_dict[co]['latitude']),
                     fill_color="red",
                     size=6,
                     fill_alpha=.9,
                     line_color="red",
                     line_alpha=0.6,
                     legend="Locality (Xi)",
                     muted_alpha=0.2)
        p.legend.click_policy = "mute"
        show(p)
Пример #15
0
def make_fitted_plot(self,
                     result,
                     filestart='fitted',
                     show=True,
                     ut=None,
                     smooth=False,
                     savepng=False):
    curdoc().theme = Theme(BOKEH_THEME_FILE)

    if smooth:
        kernel = Gaussian2DKernel(x_stddev=1)
        source = convolve(result['abundance'], kernel, boundary='wrap')
        packets = convolve(result['p_available'], kernel, boundary='wrap')
    else:
        source = result['abundance']
        packets = result['p_available']

    # Tools
    tools = ['save']

    local_time = (result['longitude'].value * 12 / np.pi + 12) % 24
    arg = np.argsort(local_time[:-1])
    source, packets = source[arg, :], packets[arg, :]

    # Distribution of available packets
    fig0 = bkp.figure(plot_width=WIDTH,
                      plot_height=HEIGHT,
                      title=f'{self.species}, {self.query}, Available Packets',
                      x_axis_label='Local Time (hr)',
                      y_axis_label='Latitude (deg)',
                      x_range=[0, 24],
                      y_range=[-90, 90],
                      tools=tools)
    fig0.title.text_font_size = FONTSIZE
    fig0.xaxis.axis_label_text_font_size = FONTSIZE
    fig0.yaxis.axis_label_text_font_size = FONTSIZE
    fig0.xaxis.major_label_text_font_size = NUMFONTSIZE
    fig0.yaxis.major_label_text_font_size = NUMFONTSIZE
    fig0.xaxis.ticker = FixedTicker(ticks=[0, 6, 12, 18, 24])
    fig0.yaxis.ticker = FixedTicker(ticks=[-90, 45, 0, 45, 90])

    fig0.image(image=[packets.transpose()],
               x=0,
               y=-90,
               dw=24,
               dh=180,
               palette='Spectral11')

    # Distribution of packets used in the final model
    fig1 = bkp.figure(plot_width=WIDTH,
                      plot_height=HEIGHT,
                      title=f'{self.species}, {self.query}, Packets Used',
                      x_axis_label='Local Time (hr)',
                      y_axis_label='Latitude (deg)',
                      x_range=[0, 24],
                      y_range=[-90, 90],
                      tools=tools)
    fig1.title.text_font_size = FONTSIZE
    fig1.xaxis.axis_label_text_font_size = FONTSIZE
    fig1.yaxis.axis_label_text_font_size = FONTSIZE
    fig1.xaxis.major_label_text_font_size = NUMFONTSIZE
    fig1.yaxis.major_label_text_font_size = NUMFONTSIZE
    fig1.xaxis.ticker = FixedTicker(ticks=[0, 6, 12, 18, 24])
    fig1.yaxis.ticker = FixedTicker(ticks=[-90, 45, 0, 45, 90])

    fig1.image(image=[source.transpose()],
               x=0,
               y=-90,
               dw=24,
               dh=180,
               palette='Spectral11')

    fig2 = bkp.figure(
        plot_width=WIDTH,
        plot_height=HEIGHT,
        title=f'{self.species}, {self.query}, Speed Distribution',
        x_axis_label='Speed (km/s)',
        y_axis_label='Relative Number',
        y_range=[0, 1.2],
        tools=tools)
    fig2.title.text_font_size = FONTSIZE
    fig2.xaxis.axis_label_text_font_size = FONTSIZE
    fig2.yaxis.axis_label_text_font_size = FONTSIZE
    fig2.xaxis.major_label_text_font_size = NUMFONTSIZE
    fig2.yaxis.major_label_text_font_size = NUMFONTSIZE

    fig2.line(x=result['velocity'][:-1],
              y=result['v_available'],
              legend_label='Packets Available',
              color='red')
    fig2.line(x=result['velocity'][:-1],
              y=result['vdist'],
              legend_label='Packets Used',
              color='blue')

    # Full orbit time series
    # Format the date correction
    self.data['utcstr'] = self.data['utc'].apply(lambda x: x.isoformat()[0:19])

    # Put the dataframe in a useable form
    self.data['lower'] = self.data.radiance - self.data.sigma
    self.data['upper'] = self.data.radiance + self.data.sigma
    self.data['lattandeg'] = self.data.lattan * 180 / np.pi

    m = self.data[self.data.alttan != self.data.alttan.max()].alttan.max()
    col = np.interp(self.data.alttan, np.linspace(0, m, 256),
                    np.arange(256)).astype(int)
    self.data['color'] = [Turbo256[c] for c in col]
    source = bkp.ColumnDataSource(self.data)

    # Tools
    tools = [
        'pan', 'box_zoom', 'wheel_zoom', 'xbox_select', 'hover', 'reset',
        'save'
    ]

    # tool tips
    tips = [('index', '$index'), ('UTC', '@utcstr'),
            ('Radiance', '@radiance{0.2f} kR'),
            ('LTtan', '@loctimetan{2.1f} hr'),
            ('Lattan', '@lattandeg{3.1f} deg'), ('Alttan', '@alttan{0.f} km')]

    # Make the radiance figure
    title_ = f'{self.species}, {self.query}'
    if ut is not None:
        title_ += f', UTC = {ut.isoformat()}'
    else:
        pass

    fig3 = bkp.figure(plot_width=WIDTH,
                      plot_height=HEIGHT,
                      x_axis_type='datetime',
                      title=title_,
                      x_axis_label='UTC',
                      y_axis_label='Radiance (kR)',
                      y_range=[0, self.data.radiance.max() * 1.5],
                      tools=tools,
                      active_drag="xbox_select")
    fig3.title.text_font_size = FONTSIZE
    fig3.xaxis.axis_label_text_font_size = FONTSIZE
    fig3.yaxis.axis_label_text_font_size = FONTSIZE
    fig3.xaxis.major_label_text_font_size = NUMFONTSIZE
    fig3.yaxis.major_label_text_font_size = NUMFONTSIZE

    # plot the data
    dplot = fig3.circle(x='utc',
                        y='radiance',
                        size=7,
                        color='black',
                        legend_label='Data',
                        hover_color='yellow',
                        source=source,
                        selection_color='orange')
    fig3.line(x='utc',
              y='radiance',
              color='black',
              legend_label='Data',
              source=source)
    fig3.xaxis.ticker = DatetimeTicker(num_minor_ticks=5)

    # Add error bars
    fig3.add_layout(
        Whisker(source=source, base='utc', upper='upper', lower='lower'))
    renderers = [dplot]

    # Plot the model
    col = color_generator()
    modplots, maskedplots = [], []
    for modkey, result in self.model_result.items():
        if result.fitted:
            c = next(col)
            fig3.line(x='utc',
                      y=modkey,
                      source=source,
                      legend_label=result.label,
                      color=c)

            maskkey = modkey.replace('model', 'mask')
            mask = self.data[maskkey].to_list()
            view = CDSView(source=source, filters=[BooleanFilter(mask)])
            modplots.append(
                fig3.circle(x='utc',
                            y=modkey,
                            size=7,
                            color=c,
                            source=source,
                            legend_label=result.label,
                            view=view))

            maskkey = modkey.replace('model', 'mask')
            mask = np.logical_not(self.data[maskkey]).to_list()
            view = CDSView(source=source, filters=[BooleanFilter(mask)])
            maskedplots.append(
                fig3.circle(x='utc',
                            y=modkey,
                            size=7,
                            source=source,
                            line_color=c,
                            fill_color='yellow',
                            view=view,
                            legend_label=result.label +
                            '(Data Point Not Used)'))
            renderers.extend(modplots)
            renderers.extend(maskedplots)

        if ut is not None:
            yr = fig3.y_range
            fig3.line(x=[ut, ut], y=[0, 1e5], color='purple')
            fig3.y_range = yr
        else:
            pass

    datahover = HoverTool(tooltips=tips, renderers=renderers)
    fig3.add_tools(datahover)

    grid = gridplot([[fig3, fig2], [fig0, fig1]])

    # Save png version
    if savepng:
        export_png(grid, filename=filestart + '.png')
    else:
        pass

    bkp.output_file(filestart + '.html')
    bkp.save(grid)  # html files not needed

    if show:
        bkp.show(grid)
    else:
        pass

    return grid
Пример #16
0
# yrs=yrs.apply(str)
# yrs = yrs.tolist()
x = oo_Year_Gender.Year  #x data: years

#Figure Stuff
p = figure(
    x_range=[1895, 2009],
    y_range=[-10, 1300],
    x_axis_label='Year',
    y_axis_label='Medal Count',  #"pan,box_zoom,reset,save,hover"
    title="Total Medal Count by Gender per Year")

#Filter Data for World War cancellation
view = CDSView(filters=[
    IndexFilter([
        0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
        23, 24, 25, 26, 27, 28
    ])
])
patch1 = p.patch(x=[1912, 1912, 1920, 1920],
                 y=[-10, 1300, 1300, -10],
                 color='white',
                 alpha=0.22,
                 line_width=0)
patch2 = p.patch(x=[1936, 1936, 1948, 1948],
                 y=[-10, 1300, 1300, -10],
                 color='white',
                 alpha=0.22,
                 line_width=0)
p.add_tools(
    HoverTool(renderers=[patch1],
              tooltips=[
Пример #17
0
from bokeh.layouts import row

# Import the data
from read_nba_data import player_stats

# Output to a static html file
output_file('lebron_vs_durant.html',
            title='LeBron James vs. Kevin Durant')

# Store the data in a ColumnDataSource
player_gm_stats = ColumnDataSource(player_stats)

# Create a view for each player
lebron_filters = [GroupFilter(column_name='playFNm', group='LeBron'),
                  GroupFilter(column_name='playLNm', group='James')]
lebron_view = CDSView(source=player_gm_stats,
                      filters=lebron_filters)

durant_filters = [GroupFilter(column_name='playFNm', group='Kevin'),
                  GroupFilter(column_name='playLNm', group='Durant')]
durant_view = CDSView(source=player_gm_stats,
                      filters=durant_filters)

# Consolidate the common keyword arguments in dicts
common_figure_kwargs = {
    'plot_width': 400,
    'x_axis_label': 'Points',
    'toolbar_location': None,
}
common_circle_kwargs = {
    'x': 'playPTS',
    'y': 'playTRB',
Пример #18
0
    def bkplot(self,
               x,
               y,
               color='None',
               radii='None',
               ps=20,
               minps=0,
               alpha=0.8,
               pw=600,
               ph=400,
               palette='Inferno256',
               style='smapstyle',
               Hover=True,
               title='',
               table=False,
               table_width=600,
               table_height=150,
               add_colorbar=True,
               Periodic_color=False,
               return_datasrc=False,
               frac_load=1.0,
               marker=['circle'],
               seed=0,
               **kwargs):
        from bokeh.layouts import row, widgetbox, column, Spacer
        from bokeh.models import HoverTool, TapTool, FixedTicker, Circle, WheelZoomTool
        from bokeh.models import CustomJS, Slider, Rect, ColorBar, HoverTool, LinearColorMapper, BasicTicker
        from bokeh.plotting import figure
        import bokeh.models.markers as Bokeh_markers
        from bokeh.models import ColumnDataSource, CDSView, IndexFilter
        from bokeh.palettes import all_palettes, Spectral6, Inferno256, Viridis256, Greys256, Magma256, Plasma256
        from bokeh.palettes import Spectral, Inferno, Viridis, Greys, Magma, Plasma
        from bokeh.models import LogColorMapper, LogTicker, ColorBar, BasicTicker, LinearColorMapper
        from bokeh.models.widgets import DataTable, TableColumn, NumberFormatter, Div
        import pandas as pd
        #        if (title==''): title=self.name
        fulldata = self.pd
        idx = np.arange(len(fulldata))
        fulldata['id'] = idx
        nload = int(frac_load * len(fulldata))
        np.random.seed(seed)
        np.random.shuffle(idx)
        idload = np.sort(idx[0:nload])
        data = self.pd.iloc[idload].copy()
        if palette == 'cosmo': COLORS = cosmo()
        else: COLORS = locals()[palette]

        marklist = [
            'circle', 'diamond', 'triangle', 'square', 'asterisk', 'cross',
            'inverted_triangle'
        ]
        if not marker[0] in marklist: marker = marklist
        # TOOLS="resize,crosshair,pan,wheel_zoom,reset,tap,save,box_select,box_zoom,lasso_select"
        TOOLS = "pan,reset,tap,save,box_zoom,lasso_select"
        wheel_zoom = WheelZoomTool(dimensions='both')
        if Hover:
            proplist = []
            for prop in data.columns:
                if prop not in [
                        "CV1", "CV2", "Cv1", "Cv2", "cv1", "cv2", "colors",
                        "radii", "id"
                ]:
                    proplist.append((prop, '@' + prop))
            hover = HoverTool(names=["mycircle"], tooltips=[("id", '@id')])
            for prop in proplist:
                hover.tooltips.append(prop)
            plot = figure(title=title,
                          plot_width=pw,
                          active_scroll=wheel_zoom,
                          plot_height=ph,
                          tools=[TOOLS, hover, wheel_zoom],
                          **kwargs)
        else:
            plot = figure(title=title,
                          plot_width=pw,
                          active_scroll=wheel_zoom,
                          plot_height=ph,
                          tools=[TOOLS],
                          **kwargs)

# selection glyphs and plot styles
        mdict = {
            'circle': 'Circle',
            'diamond': 'Diamond',
            'triangle': 'Triangle',
            'square': 'Square',
            'asterisk': 'Asterisk',
            'cross': 'Cross',
            'inverted_triangle': 'InvertedTriangle'
        }
        initial_circle = Circle(x='x', y='y')
        selected_circle = getattr(Bokeh_markers,
                                  mdict[marker[0]])(fill_alpha=0.7,
                                                    fill_color="blue",
                                                    size=ps * 1.5,
                                                    line_color="blue")
        nonselected_circle = getattr(Bokeh_markers,
                                     mdict[marker[0]])(fill_alpha=alpha * 0.5,
                                                       fill_color='colors',
                                                       line_color='colors',
                                                       line_alpha=alpha * 0.5)
        # set up variable point size
        if radii == 'None':
            r = [ps for i in range(len(data))]
            data['radii'] = r
        else:
            if data[radii].dtype == 'object':  # Categorical variable for radii
                grouped = data.groupby(radii)
                i = 0
                r = np.zeros(len(data))
                for group_item in grouped.groups.keys():
                    r[grouped.groups[group_item].tolist()] = i**2
                    i = i + 2
            else:
                r = [val for val in data[radii]]
            rn = self.normalize(r)
            rad = [minps + ps * np.sqrt(val) for val in rn]
            data['radii'] = rad

# setup variable point color
        if color == 'None':
            c = ["#31AADE" for i in range(len(data))]
            data['colors'] = c
            datasrc = ColumnDataSource(data)
            getattr(plot, marker[0])(x,
                                     y,
                                     source=datasrc,
                                     size='radii',
                                     fill_color='colors',
                                     fill_alpha=alpha,
                                     line_color='colors',
                                     line_alpha=alpha,
                                     name="mycircle")
            renderer = plot.select(name="mycircle")
            renderer.selection_glyph = selected_circle
            renderer.nonselection_glyph = nonselected_circle
        else:
            if data[color].dtype == 'object':  # Categorical variable for colors
                grouped = data.groupby(color)
                # COLORS=Spectral[len(grouped)]
                i = 0
                nc = len(COLORS)
                istep = int(nc / len(grouped))
                cat_colors = []
                for group_item in grouped.groups.keys():
                    #  data.loc[grouped.groups[group_item],'colors']=COLORS[i]
                    # print(group_item,COLORS[i])
                    i = min(i + istep, nc - 1)
                    cat_colors.append(COLORS[i])
                #colors=[ '#d53e4f', '#3288bd','#fee08b', '#99d594']
                datasrc = ColumnDataSource(data)
                view = []
                # used_markers=[]
                # marker=['circle','diamond','triangle','square','asterisk','cross','inverted_triangle']
                #while True:
                #    for x in marker:
                #        used_markers.append(x)
                #    if len(used_markers)>len(grouped): break
                i = 0
                #print used_markers
                for group_item in grouped.groups.keys():
                    view.append(
                        CDSView(
                            source=datasrc,
                            filters=[IndexFilter(grouped.groups[group_item])]))
                    cname = 'mycircle' + str(i)
                    #print used_markers[i]
                    try:
                        mk = marker[i]
                    except:
                        mk = marker[0]
                    getattr(plot, mk)(x,
                                      y,
                                      source=datasrc,
                                      size='radii',
                                      fill_color=cat_colors[i],
                                      muted_color=cat_colors[i],
                                      muted_alpha=0.2,
                                      fill_alpha=alpha,
                                      line_alpha=alpha,
                                      line_color=cat_colors[i],
                                      name=cname,
                                      legend=group_item,
                                      view=view[i])
                    selected_mk = getattr(Bokeh_markers,
                                          mdict[mk])(fill_alpha=0.7,
                                                     fill_color="blue",
                                                     size=ps * 1.5,
                                                     line_color="blue",
                                                     line_alpha=0.7)
                    nonselected_mk = getattr(Bokeh_markers, mdict[mk])(
                        fill_alpha=alpha * 0.5,
                        fill_color=cat_colors[i],
                        line_color=cat_colors[i],
                        line_alpha=alpha * 0.5)
                    renderer = plot.select(name=cname)
                    renderer.selection_glyph = selected_mk
                    renderer.nonselection_glyph = nonselected_mk
                    i += 1
                plot.legend.location = "top_left"
                plot.legend.orientation = "vertical"
                plot.legend.click_policy = "hide"
            else:
                if Periodic_color:  # if periodic property then generate periodic color palatte
                    blendcolor = interpolate(COLORS[-1], COLORS[0],
                                             len(COLORS) / 5)
                    COLORS = COLORS + blendcolor
                groups = pd.cut(data[color].values, len(COLORS))
                c = [COLORS[xx] for xx in groups.codes]
                data['colors'] = c
                datasrc = ColumnDataSource(data)
                getattr(plot, marker[0])(x,
                                         y,
                                         source=datasrc,
                                         size='radii',
                                         fill_color='colors',
                                         fill_alpha=alpha,
                                         line_color='colors',
                                         line_alpha=alpha,
                                         name="mycircle")
                renderer = plot.select(name="mycircle")
                renderer.selection_glyph = selected_circle
                renderer.nonselection_glyph = nonselected_circle
                color_mapper = LinearColorMapper(COLORS,
                                                 low=data[color].min(),
                                                 high=data[color].max())
                colorbar = ColorBar(color_mapper=color_mapper,
                                    ticker=BasicTicker(),
                                    label_standoff=4,
                                    border_line_color=None,
                                    location=(0, 0),
                                    orientation="vertical")
                colorbar.background_fill_alpha = 0
                colorbar.border_line_alpha = 0
                if add_colorbar:
                    plot.add_layout(colorbar, 'left')
        # Overview plot
        oplot = figure(title='',
                       plot_width=200,
                       plot_height=200,
                       toolbar_location=None)
        oplot.circle(x,
                     y,
                     source=datasrc,
                     size=4,
                     fill_alpha=0.6,
                     line_color=None,
                     name="mycircle")
        orenderer = oplot.select(name="mycircle")
        orenderer.selection_glyph = selected_circle
        # orenderer.nonselection_glyph = nonselected_circle
        rectsource = ColumnDataSource({'xs': [], 'ys': [], 'wd': [], 'ht': []})
        jscode = """
                var data = source.data;
                var start = range.start;
                var end = range.end;
                data['%s'] = [start + (end - start) / 2];
                data['%s'] = [end - start];
                source.change.emit();
             """
        plot.x_range.callback = CustomJS(args=dict(source=rectsource,
                                                   range=plot.x_range),
                                         code=jscode % ('xs', 'wd'))
        plot.y_range.callback = CustomJS(args=dict(source=rectsource,
                                                   range=plot.y_range),
                                         code=jscode % ('ys', 'ht'))
        rect = Rect(x='xs',
                    y='ys',
                    width='wd',
                    height='ht',
                    fill_alpha=0.1,
                    line_color='black',
                    fill_color='red')
        oplot.add_glyph(rectsource, rect)

        # plot style
        plot.toolbar.logo = None
        oplot.toolbar.logo = None
        if style == 'smapstyle': plist = [plot, oplot]
        else: plist = [oplot]
        for p in plist:
            p.xgrid.grid_line_color = None
            p.ygrid.grid_line_color = None
            p.xaxis[0].ticker = FixedTicker(ticks=[])
            p.yaxis[0].ticker = FixedTicker(ticks=[])
            p.outline_line_width = 0
            p.outline_line_alpha = 0
            p.background_fill_alpha = 0
            p.border_fill_alpha = 0
            p.xaxis.axis_line_width = 0
            p.xaxis.axis_line_color = "white"
            p.yaxis.axis_line_width = 0
            p.yaxis.axis_line_color = "white"
            p.yaxis.axis_line_alpha = 0


# table
        if table:
            tcolumns = [
                TableColumn(field='id',
                            title='id',
                            formatter=NumberFormatter(format='0'))
            ]
            for prop in data.columns:
                if prop not in [
                        "CV1", "CV2", "Cv1", "Cv2", "cv1", "cv2", "colors",
                        'id', "radii"
                ]:
                    if data[prop].dtype == 'object':
                        tcolumns.append(TableColumn(field=prop, title=prop))
                    if data[prop].dtype == 'float64':
                        tcolumns.append(
                            TableColumn(
                                field=prop,
                                title=prop,
                                formatter=NumberFormatter(format='0.00')))
                    if data[prop].dtype == 'int64':
                        tcolumns.append(
                            TableColumn(field=prop,
                                        title=prop,
                                        formatter=NumberFormatter(format='0')))
            data_table = DataTable(source=datasrc,
                                   fit_columns=True,
                                   scroll_to_selection=True,
                                   columns=tcolumns,
                                   name="Property Table",
                                   width=table_width,
                                   height=table_height)
            div = Div(text="""<h6><b> Property Table </b> </h6> <br>""",
                      width=600,
                      height=10)
            if return_datasrc:
                return plot, oplot, column(widgetbox(div), Spacer(height=10),
                                           widgetbox(data_table)), datasrc
            else:
                return plot, oplot, column(widgetbox(div), Spacer(height=10),
                                           widgetbox(data_table))
        else:
            return plot, oplot
Пример #19
0
    def to_html(self, dir_plot_destination):
        fn_dest = join(dir_plot_destination,
                       "t16a-postprocessing_dashboard.html")
        output_file(fn_dest)

        source = ColumnDataSource(self.df)

        init_group = 'Lebanon'
        gf = GroupFilter(column_name='CountryProv', group=init_group)
        view1 = CDSView(source=source, filters=[gf])

        plot_size_and_tools = {
            'plot_height': 300,
            'plot_width': 300,
            'tools': ['box_select', 'reset', 'help', 'box_zoom'],
            'x_axis_type': 'datetime'
        }

        p_cc_ori = figure(title="Confirmed cases: original",
                          **plot_size_and_tools)
        c_cc_ori = p_cc_ori.circle(x='Date',
                                   y='ConfirmedCases',
                                   source=source,
                                   color='black',
                                   view=view1)

        p_cc_cl = figure(title="Confirmed cases: eased spikes",
                         **plot_size_and_tools)
        c_cc_cl = p_cc_cl.circle(x='Date',
                                 y='cases_cumulClean',
                                 source=source,
                                 color='red',
                                 view=view1)

        p_cto = figure(title="Cumulative Tests: original",
                       **plot_size_and_tools)
        c_cto = p_cto.circle(x='Date',
                             y='total_cumul.all',
                             source=source,
                             color='black',
                             view=view1)

        p_ci = figure(title="Cumulative Tests: interpolated",
                      **plot_size_and_tools)
        c_ci = p_ci.circle(x='Date',
                           y='tests_cumulInterpolated',
                           source=source,
                           view=view1,
                           color='red')

        p_cns = figure(title="Cumulative Tests: eased spikes",
                       **plot_size_and_tools)
        c_cns = p_cns.circle(x='Date',
                             y='tests_cumulNoSpike',
                             source=source,
                             view=view1,
                             color='red')

        g = gridplot([[p_cc_ori, p_cc_cl], [p_cto, p_ci, p_cns]])

        # from https://docs.bokeh.org/en/latest/docs/user_guide/interaction/widgets.html#select
        callback = CustomJS(args=dict(vf=c_cc_ori.view.filters[0],
                                      source=source),
                            code="""
    console.log(vf.group);
    console.log(cb_obj.value);
        vf.group = cb_obj.value;
        source.change.emit();
    """)
        from bokeh.models import Select
        select = Select(title="Country/State:",
                        value=init_group,
                        options=list(self.df.CountryProv.unique()))
        select.js_on_change('value', callback)

        layout = column(select, g)
        save(layout)
        print(f"Saved to {fn_dest}")
Пример #20
0
            sprint.query(
                'Medal == "gold" and Year in [1988, 1968, 1936, 1896]').index))
]

medal = Circle(x="MetersBack",
               y="Year",
               size=10,
               fill_color="MedalFill",
               line_color="MedalLine",
               fill_alpha=0.5)
medal_renderer = plot.add_glyph(source, medal)

#sprint[sprint.Medal=="gold" * sprint.Year in [1988, 1968, 1936, 1896]]
plot.add_glyph(source,
               Text(x="MetersBack", y="Year", x_offset=10, text="Name"),
               view=CDSView(source=source, filters=filters))

plot.add_glyph(
    source,
    Text(x=7.5,
         y=1942,
         text=["No Olympics in 1940 or 1944"],
         text_font_style="italic",
         text_color="silver"))

tooltips = """
<div>
    <span style="font-size: 15px;">@Name</span>&nbsp;
    <span style="font-size: 10px; color: #666;">(@Abbrev)</span>
</div>
<div>
Пример #21
0
from bokeh.layouts import gridplot
from bokeh.models import CDSView, ColumnDataSource, IndexFilter
from bokeh.plotting import figure, show

source = ColumnDataSource(data=dict(x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5]))
view = CDSView(filters=[IndexFilter([0, 2, 4])])

tools = ["box_select", "hover", "reset"]
p = figure(height=300, width=300, tools=tools)
p.circle(x="x", y="y", size=10, hover_color="red", source=source)

p_filtered = figure(height=300, width=300, tools=tools)
p_filtered.circle(x="x", y="y", size=10, hover_color="red", source=source, view=view)

show(gridplot([[p, p_filtered]]))
from bokeh.layouts import gridplot
from bokeh.models import BooleanFilter, CDSView, ColumnDataSource
from bokeh.plotting import figure, show

source = ColumnDataSource(data=dict(x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5]))
booleans = [True if y_val > 2 else False for y_val in source.data['y']]
view = CDSView(filter=BooleanFilter(booleans))

tools = ["box_select", "hover", "reset"]
p = figure(height=300, width=300, tools=tools)
p.circle(x="x", y="y", size=10, hover_color="red", source=source)

p_filtered = figure(height=300,
                    width=300,
                    tools=tools,
                    x_range=p.x_range,
                    y_range=p.y_range)
p_filtered.circle(x="x",
                  y="y",
                  size=10,
                  hover_color="red",
                  source=source,
                  view=view)

show(gridplot([[p, p_filtered]]))
Пример #23
0
# General API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------

# TODO: ideally, the list of arguments should be received directly from
# GlyphRenderer, but such case requires a system that would be able to generate
# acceptable values for parameters
_renderer_args_values = {
    'name': [None, '', 'test name'],
    'x_range_name': [None, '', 'x range'],
    'y_range_name': [None, '', 'y range'],
    'level': [None, 'overlay'],
    'view': [None, CDSView(source=None)],
    'visible': [None, False, True],
    'muted': [None, False, True]
}


@pytest.mark.parametrize('arg,values', [(arg, _renderer_args_values[arg])
                                        for arg in RENDERER_ARGS])
@pytest.mark.unit
def test__glyph_receives_renderer_arg(arg, values):
    for value in values:
        with mock.patch('bokeh.plotting._renderer.GlyphRenderer',
                        autospec=True) as gr_mock:

            def foo(**kw):
                pass
from bokeh.layouts import gridplot
from bokeh.models import CDSView, ColumnDataSource, IndexFilter
from bokeh.plotting import figure, show

# create ColumnDataSource from a dict
source = ColumnDataSource(data=dict(x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5]))

# create a view using an IndexFilter with the index positions [0, 2, 4]
view = CDSView(source=source, filters=[IndexFilter([0, 2, 4])])

# setup tools
tools = ["box_select", "hover", "reset"]

# create a first plot with all data in the ColumnDataSource
p = figure(height=300, width=300, tools=tools)
p.circle(x="x", y="y", size=10, hover_color="red", source=source)

# create a second plot with a subset of ColumnDataSource, based on view
p_filtered = figure(height=300, width=300, tools=tools)
p_filtered.circle(x="x",
                  y="y",
                  size=10,
                  hover_color="red",
                  source=source,
                  view=view)

# show both plots next to each other in a gridplot layout
show(gridplot([[p, p_filtered]]))
Пример #25
0
from bokeh.layouts import gridplot
from bokeh.models import BooleanFilter, CDSView, ColumnDataSource
from bokeh.plotting import figure, show

np.random.seed(42)

df = pd.DataFrame({
    'x':np.random.randint(0, 10, 15),
    'y':np.random.randint(0, 10, 15)
})


source = ColumnDataSource(df)
booleans = [True if y_val > 7 else False for y_val in source.data['y']]
view = CDSView(source=source, filters=[BooleanFilter(booleans)])
TOOLS = ['box_select', 'hover', 'reset']
p = figure(
    plot_height=300,
    plot_width=300,
    tools=TOOLS
)
p.circle(x='x', y='y', size=10, hover_color='red', source=source)

p_filtered = figure(
    plot_height=300,
    plot_width=300,
    tools=TOOLS,
    x_range = p.x_range,
    y_range = p.y_range
)
Пример #26
0
def pca_scatter(df=None,
                out_file='pca.html',
                annotate=False,
                text_size='6pt',
                marker_size=15,
                stretch='both'):
    # sample
    if df is None:
        df = pd.DataFrame(
            dict(x=[1, 2, 3, 4, 5],
                 y=[2, 5, 8, 2, 7],
                 group=['g1', 'g1', 'g1', 'g2', 'g2'],
                 group2=['g3', 'g3', 'g4', 'g4', 'g4']))
        df.index = ['A', 'b', 'C', 'd', 'E']
        df.index.name = 'name'

    # get group scheme
    if df.shape[1] < 3:
        df.loc[:, 'group'] = df.index

    group_scheme_list = list(df.columns[2:])

    # all markers
    marker_pool = [
        "asterisk", "circle", "cross", "square", "diamond", "triangle",
        "inverted_triangle", "x", "diamond_cross", "circle_x", "square_cross",
        "square_x", "dash", "circle_cross"
    ]

    # match markers
    for group_scheme in group_scheme_list:
        groups = sorted(set(df[group_scheme]))
        color_pool = get_color_pool(len(groups))
        if len(groups) <= len(marker_pool):
            marker_dict = dict(zip(groups, marker_pool))
            color_dict = dict(zip(groups, color_pool))
            df.loc[:, group_scheme +
                   '_marker'] = [marker_dict[x] for x in df[group_scheme]]
            df.loc[:, group_scheme +
                   '_color'] = [color_dict[x] for x in df[group_scheme]]
        else:
            color_dict = dict(zip(groups, color_pool))
            df.loc[:, group_scheme + '_marker'] = "circle"
            df.loc[:, group_scheme +
                   '_color'] = [color_dict[x] for x in df[group_scheme]]

    #
    source = ColumnDataSource(df)
    plot_options = dict(
        # width=250,
        # plot_height=500,
        tools='pan,wheel_zoom,box_select, reset,save', )

    # plot
    plots = list()
    for ind, group_scheme in enumerate(group_scheme_list):
        if ind > 0:
            plot_options['x_range'] = plots[0].x_range
            plot_options['y_range'] = plots[0].y_range
        s = figure(**plot_options)
        hover = HoverTool(tooltips=[
            ("group", "@{}".format(df.index.name)),
        ])
        s.add_tools(hover)
        groups = sorted(set(df[group_scheme]))
        legend_items = list()
        for group in groups:
            tmp = s.scatter(
                x=df.columns[0],
                y=df.columns[1],
                marker=group_scheme + '_marker',
                source=source,
                size=marker_size,
                color=group_scheme + '_color',
                alpha=0.6,
                # legend=group,
                view=CDSView(source=source,
                             filters=[
                                 GroupFilter(column_name=group_scheme,
                                             group=group)
                             ]))
            legend_items.append((group, [tmp]))
        # 如此可以保证legend在图形外面
        legend = Legend(items=legend_items, location="center")
        s.add_layout(legend, 'right')

        if annotate:
            labels = LabelSet(x=df.columns[0],
                              y=df.columns[1],
                              text=df.index.name,
                              level='glyph',
                              x_offset=5,
                              y_offset=2,
                              source=source,
                              text_font_size=text_size,
                              render_mode='canvas')
            s.add_layout(labels)

        s.legend.location = 'top_left'
        s.legend.click_policy = "hide"
        s.xaxis.axis_label = df.columns[0]
        s.yaxis.axis_label = df.columns[1]
        plots.append(s)

    p = gridplot(plots, sizing_mode='stretch_{}'.format(stretch), ncols=2)
    output_file(out_file, title="PCA Scatter")
    save(p)
Пример #27
0
def scatterplot_comparison(
    controls_df: pd.DataFrame,
    result_df: pd.DataFrame,
    data_label: str,
    *,
    ref_label: Union[str, List[str]] = None,
    category_labels: Dict = None,
    controls_name: str = 'controls',
    result_name: str = 'model',
    size: float = 7.5,
    fill_alpha: float = 0.2,
    facet_col: str = None,
    facet_col_wrap: int = 2,
    facet_sort_order: bool = True,
    facet_sync_axes: str = 'both',
    hover_col: Union[str, List[str]] = None,
    glyph_col: str = None,
    glyph_legend: bool = True,
    glyph_legend_location: str = 'bottom_right',
    glyph_legend_label_text_font_size: str = '11px',
    figure_title: str = None,
    plot_height: int = None,
    identity_line: bool = True,
    identity_colour: str = 'red',
    identity_width: int = 2,
    color_palette: Dict[int, Any] = Category20,
    calc_pct_diff: bool = True,
    totals_in_titles: bool = True,
    filter_zero_rows: bool = True
) -> Tuple[pd.DataFrame, Union[Column, Figure, GridBox]]:
    """Creates an interactive Bokeh-based scatter plot to compare data.

    Args:
        controls_df (pd.DataFrame): A DataFrame containing control values. Must be in wide-format where rows represent
            a reference (e.g. count station, TAZ, geography, etc.) and columns represent the data categories.
        result_df (pd.DataFrame): A DataFrame containing modelled values. Uses the same format as `controls_df`.
        data_label (str): The name to use for the data represented by the `controls_df` and `result_df` columns.
        ref_label (Union[str, List[str]], optional): Defaults to ``None``. The name(s) corresponding to the
            ``controls_df`` and ``result_df`` indices. The function will try to infer the name(s) from indices of the
            source DataFrames. If the indicies of the DataFrames are not set, then values must be set for this
            parameter, otherwise an error will be raised. If providing a value to this parameter and the indices of the
            source DataFrames are MultiIndex objects, then the provided value must be a list of strings.
        category_labels (Dict, optional): Defaults to ``None``. Category labels used to rename the `controls_df` and
            `result_df` columns.
        controls_name (str, optional): Defaults to ``'controls'``. The name for the controls.
        result_name (str, optional): Defaults to ``'model'``. The name for the results.
        size (float, optional): Defaults to ``7.5``. The size of the scatter plot points.
        fill_alpha (float, optional): Defaults to ``0.2``. The opacity of the point fill.
        facet_col (str, optional): Defaults to ``None``. The name of the column to use for creating a facet plot.
        facet_col_wrap (int, optional): Defaults to ``2``. The number of columns to wrap subplots in the facet plot.
        facet_sort_order (bool, optional): Defaults to ``True``. A flag to render facet subplots in ascending order
            sorted by unique ``facet_col`` values.
        facet_sync_axes (str, optional): Defaults to ``'both'``. Option to sync/link facet axes. Accepts one of
            ``['both', 'x', 'y']``. Set to None to disable linked facet plot axes.
        hover_col (Union[str, List[str]], optional): Defaults to ``None``. The column names to display in the plot
            tooltips.
        glyph_col (str, optional): Defaults to ``None``. The name of the column to use for glyph coloring. A standard
            color palette will be mapped to unique ``glyph_col`` values.
        glyph_legend (bool, optional): Defaults to ``True``. A flag to enable/disable the legend if ``glyph_col`` is
            set. The legend will be included in each plot/facet subplot.
        glyph_legend_location (str, optional): Defaults to ``'bottom_right'``. The location of the glyph legend in each
            plot/facet subplot. Please refer to the Bokeh ``Legend`` documentation for acceptable values.
        glyph_legend_label_text_font_size (str, optional): Defaults to ``'11px'``. The text size of the legend labels.
        figure_title (str, optional): Defaults to ``None``. The chart title to use.
        plot_height (int, optional): Defaults to ``None``. The desired plot height. For facet plots, this value will be
            set for each subplot.
        identity_line (bool, optional): Defaults to ``True``. A flag to include an identity (1:1) line in the
            scatter plot.
        identity_colour (str, optional): Defaults to ``'red'``. The colour to use for the identity line. Accepts html
            colour names.
        identity_width (int, optional): Defaults to ``2``. The line width to use for the identity line.
        color_palette (Dict[str, Any], optional): Defaults to ``Category20``. The Bokeh color palette to use.
        calc_pct_diff (bool, optional): Defaults to ``True``. Include percent difference calculation in DataFrame output
        totals_in_titles (bool, optional): Defaults to ``True``. Include the control and result totals in plot title.
        filter_zero_rows (bool, optional): Defaults to ``True``. Filter out comparisons where controls and results are
            both zeros.

    Returns:
        Tuple[pd.DataFrame, Union[Column, Figure, GridBox]]
    """

    if not controls_df.index.equals(result_df.index):
        warnings.warn(
            'Indices for `controls_df` and `result_df` are not identical; function may not produce desired '
            'results')
    if not controls_df.columns.equals(result_df.columns):
        warnings.warn(
            'Columns for `controls_df` and `result_df` are not identical; function may not produce desired '
            'results')

    if ref_label is None:
        assert np.all(controls_df.index.names == result_df.index.names), 'Unable to resolve different index names, ' \
                                                                         'please specify values for `ref_label` instead'
        assert not (None in controls_df.index.names
                    ), 'Some index levels in `controls_df` do not have names'
        assert not (None in result_df.index.names
                    ), 'Some index levels in `result_df` do not have names'
        ref_label = list(controls_df.index.names)
    elif isinstance(ref_label, Hashable):
        ref_label = [ref_label]
    elif isinstance(ref_label, List):
        pass
    else:
        raise RuntimeError('Invalid data type provided for `ref_label`')

    if hover_col is None:
        hover_col = []
    if isinstance(hover_col, Hashable):
        hover_col = [hover_col]
    elif isinstance(hover_col, List):
        pass
    else:
        raise RuntimeError('Invalid data type provided for `ref_label`')

    # Prepare data for plotting
    df = controls_df.stack()
    df.index.names = [*ref_label, data_label]
    df = df.to_frame(name=controls_name)

    df[result_name] = result_df.stack()
    df[result_name].fillna(0, inplace=True)

    if filter_zero_rows:
        df = df[df.sum(axis=1) > 0].copy()

    df.reset_index(inplace=True)

    if category_labels is not None:
        df[data_label] = df[data_label].map(category_labels)

    fig_df = df.copy()
    if totals_in_titles:
        label_totals = fig_df.groupby(data_label)[[controls_name,
                                                   result_name]].sum()
        label_totals[
            'label'] = label_totals.index + f' ({controls_name}=' + label_totals[
                controls_name].map(
                    '{:,.0f}'.format
                ) + f', {result_name}=' + label_totals[result_name].map(
                    '{:,.0f}'.format) + ')'
        fig_df[data_label] = fig_df[data_label].map(label_totals['label'])

    if glyph_col is not None:
        n_colors = max(len(fig_df[glyph_col].unique()), 3)
        color_palette = color_palette[n_colors]

    # Prepare figure formatting values
    source = ColumnDataSource(fig_df)
    tooltips = [(c, '@{%s}' % c) for c in hover_col]
    tooltips += [(controls_name, '@{%s}{0,0.0}' % controls_name),
                 (result_name, '@{%s}{0,0.0}' % result_name)]
    figure_params = _prep_figure_params(controls_name, result_name, tooltips,
                                        plot_height)
    glyph_params = {
        'source': source,
        'x': controls_name,
        'y': result_name,
        'size': size,
        'fill_alpha': fill_alpha,
        'hover_color': 'red'
    }

    slope = Slope(gradient=1,
                  y_intercept=0,
                  line_color=identity_colour,
                  line_dash='dashed',
                  line_width=identity_width)

    def apply_legend_settings(p_: Figure):
        p_.legend.visible = glyph_legend
        p_.legend.title = glyph_col
        p_.legend.location = glyph_legend_location
        p_.legend.label_text_font_size = glyph_legend_label_text_font_size
        p_.legend.click_policy = 'hide'

    # Plot figure
    if facet_col is None:  # Basic plot
        p = figure(sizing_mode='stretch_both', **figure_params)
        if glyph_col is None:  # Single glyphs
            p.circle(**glyph_params)
        else:  # Iterate through unique `glyph_col` values to use interactive legend feature
            for i, gc in enumerate(sorted(fig_df[glyph_col].unique())):
                source_view = CDSView(
                    source=source,
                    filters=[GroupFilter(column_name=glyph_col, group=gc)])
                p.circle(view=source_view,
                         legend_label=gc,
                         color=color_palette[i],
                         **glyph_params)
            apply_legend_settings(p)
        if identity_line:
            p.add_layout(slope)
        fig = p
    else:  # Facet plot
        fig = []
        facet_column_items = fig_df[facet_col].unique().tolist()
        facet_column_items = sorted(
            facet_column_items) if facet_sort_order else facet_column_items
        linked_axes = {}
        for i, fc in enumerate(facet_column_items):
            p = figure(title=fc, **figure_params, **linked_axes)
            filters = [GroupFilter(column_name=facet_col, group=fc)]
            if glyph_col is None:  # Single glyphs
                source_view = CDSView(source=source, filters=filters)
                p.circle(view=source_view, **glyph_params)
            else:  # Iterate through unique `glyph_col` values to use interactive legend feature
                for j, gc in enumerate(sorted(fig_df[glyph_col].unique())):
                    filters_ = filters + [
                        GroupFilter(column_name=glyph_col, group=gc)
                    ]
                    source_view = CDSView(source=source, filters=filters_)
                    p.circle(view=source_view,
                             legend_label=gc,
                             color=color_palette[j],
                             **glyph_params)
                apply_legend_settings(p)

            if (i == 0) and (facet_sync_axes is not None):
                if facet_sync_axes.lower() in ['x', 'both']:
                    linked_axes['x_range'] = p.x_range
                if facet_sync_axes.lower() in ['y', 'both']:
                    linked_axes['y_range'] = p.y_range

            if identity_line:
                p.add_layout(slope)

            fig.append(p)
        fig = gridplot(fig,
                       ncols=facet_col_wrap,
                       sizing_mode='stretch_both',
                       merge_tools=True)

    if figure_title is not None:
        fig = _wrap_figure_title(fig, figure_title)

    if calc_pct_diff:
        df['pct_diff'] = (df[result_name] -
                          df[controls_name]) / df[controls_name] * 100
        df['pct_diff'] = df['pct_diff'].replace([np.inf, -np.inf], np.nan)

    return df, fig
Пример #28
0
def plot_bokeh(self, filename=None, show=True, savepng=False):
    curdoc().theme = Theme(BOKEH_THEME_FILE)

    if filename is not None:
        if not filename.endswith('.html'):
            filename += '.html'
        else:
            pass
        bkp.output_file(filename)
    else:
        pass

    # Format the date correction
    self.data['utcstr'] = self.data['utc'].apply(lambda x: x.isoformat()[0:19])

    # Put the dataframe in a useable form
    self.data['lower'] = self.data.radiance - self.data.sigma
    self.data['upper'] = self.data.radiance + self.data.sigma
    self.data['lattandeg'] = self.data.lattan * 180 / np.pi

    mask = self.data.alttan != self.data.alttan.max()
    if np.any(mask):
        m = self.data[self.data.alttan != self.data.alttan.max()].alttan.max()
    else:
        m = 1e10
    col = np.interp(self.data.alttan, np.linspace(0, m, 256),
                    np.arange(256)).astype(int)
    self.data['color'] = [Turbo256[c] for c in col]
    source = bkp.ColumnDataSource(self.data)

    # Tools
    tools = [
        'pan', 'box_zoom', 'wheel_zoom', 'xbox_select', 'hover', 'reset',
        'save'
    ]

    # tool tips
    tips = [('index', '$index'), ('UTC', '@utcstr'),
            ('Radiance', '@radiance{0.2f} kR'),
            ('LTtan', '@loctimetan{2.1f} hr'),
            ('Lattan', '@lattandeg{3.1f} deg'), ('Alttan', '@alttan{0.f} km')]

    # Make the figure
    width, height = 1200, 600
    fig0 = bkp.figure(plot_width=width,
                      plot_height=height,
                      x_axis_type='datetime',
                      title=f'{self.species}, {self.query}',
                      x_axis_label='UTC',
                      y_axis_label='Radiance (kR)',
                      y_range=[0, self.data.radiance.max() * 1.5],
                      tools=tools,
                      active_drag="xbox_select")

    # plot the data
    dplot = fig0.circle(x='utc',
                        y='radiance',
                        size=7,
                        color='black',
                        legend_label='Data',
                        hover_color='yellow',
                        source=source,
                        selection_color='orange')
    fig0.line(x='utc',
              y='radiance',
              color='black',
              legend_label='Data',
              source=source)
    fig0.xaxis.ticker = DatetimeTicker(num_minor_ticks=5)

    # Add error bars
    fig0.add_layout(
        Whisker(source=source, base='utc', upper='upper', lower='lower'))
    renderers = [dplot]

    # Plot the model
    col = color_generator()
    modplots, maskedplots = [], []
    for modkey, result in self.model_result.items():
        c = next(col)
        # fig0.line(x='utc', y=modkey, source=source,
        #           legend_label=result.label, color=c)

        maskkey = modkey.replace('model', 'mask')
        mask = (self.data[maskkey]).to_list()
        view = CDSView(source=source, filters=[BooleanFilter(mask)])
        modplots.append(
            fig0.circle(x='utc',
                        y=modkey,
                        size=9,
                        color=c,
                        source=source,
                        legend_label=result.label,
                        view=view))
        maskkey = modkey.replace('model', 'mask')
        mask = np.logical_not(self.data[maskkey]).to_list()
        view = CDSView(source=source, filters=[BooleanFilter(mask)])
        maskedplots.append(
            fig0.circle(x='utc',
                        y=modkey,
                        size=9,
                        source=source,
                        line_color=c,
                        fill_color='yellow',
                        view=view,
                        legend_label=result.label + ' (Data Point Not Used)'))
        renderers.extend(modplots)
        renderers.extend(maskedplots)

    datahover = HoverTool(tooltips=tips, renderers=renderers)
    fig0.add_tools(datahover)

    ##############
    # Plot tangent point
    color_mapper = LinearColorMapper(palette="Turbo256", low=0, high=m)

    width, height = 1200, 600
    tools = [
        'pan', 'box_zoom', 'wheel_zoom', 'box_select', 'hover', 'reset', 'save'
    ]
    fig1 = bkp.figure(plot_width=width,
                      plot_height=height,
                      title=f'Tangent Point Location',
                      x_axis_label='Local Time (hr)',
                      y_axis_label='Latitude (deg)',
                      x_range=[0, 24],
                      y_range=[-90, 90],
                      tools=tools,
                      active_drag="box_select")
    tanplot = fig1.circle(x='loctimetan',
                          y='lattandeg',
                          size=5,
                          selection_color='orange',
                          hover_color='purple',
                          source=source,
                          color='color')
    fig1.xaxis.ticker = SingleIntervalTicker(interval=6, num_minor_ticks=6)
    fig1.yaxis.ticker = SingleIntervalTicker(interval=45, num_minor_ticks=3)
    color_bar = ColorBar(color_mapper=color_mapper,
                         title='Altitude (km)',
                         label_standoff=12,
                         border_line_color=None,
                         location=(0, 0))
    fig1.add_layout(color_bar, 'right')
    datahover = HoverTool(tooltips=tips, renderers=[tanplot])
    fig1.add_tools(datahover)

    grid = column(fig0, fig1)

    if filename is not None:
        bkp.output_file(filename)
        if savepng:
            export_png(grid, filename=filename.replace('.html', '.png'))
        else:
            pass
        bkp.save(grid)
    else:
        pass

    if show:
        bkp.show(grid)

    return fig0, fig1
Пример #29
0
from bokeh.layouts import gridplot
from bokeh.models import CDSView, ColumnDataSource, IndexFilter
from bokeh.plotting import figure, show

# create ColumnDataSource from a dict
source = ColumnDataSource(data=dict(x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5]))

# create a view using an IndexFilter with the index positions [0, 2, 4]
view = CDSView(filter=IndexFilter([0, 2, 4]))

# setup tools
tools = ["box_select", "hover", "reset"]

# create a first plot with all data in the ColumnDataSource
p = figure(height=300, width=300, tools=tools)
p.circle(x="x", y="y", size=10, hover_color="red", source=source)

# create a second plot with a subset of ColumnDataSource, based on view
p_filtered = figure(height=300, width=300, tools=tools)
p_filtered.circle(x="x",
                  y="y",
                  size=10,
                  hover_color="red",
                  source=source,
                  view=view)

# show both plots next to each other in a gridplot layout
show(gridplot([[p, p_filtered]]))
Пример #30
0
#        filters=[BooleanFilter(source.data['ends_with_long']), js_filter_n]),
#    height=int(HEIGHT / 1.618),
# )
# fig_n_long_ending.x_range = fig_n_not_long_ending.x_range
#
# fig_n = column([fig_n_long_ending, fig_n_not_long_ending], name='fig_n')

# Create a list of filters for each figure
filters = [js_filter(modifier=x, slider=slider) for x in range(3)]

# Make Figures
figures = []
for n in range(3):
    if n == 0:
        fig = main_fig(name="fig_n",
                       view=CDSView(source=source, filters=[filters[n]]),
                       height=HEIGHT)
    elif n == 1:
        fig = main_fig(name=f"fig_n_{n}",
                       view=CDSView(source=source, filters=[filters[n]]),
                       height=int(HEIGHT / 1.618))
    elif n == 2:
        fig = main_fig(name=f"fig_n_{n}",
                       view=CDSView(source=source, filters=[filters[n]]),
                       height=HEIGHT - int(HEIGHT / 1.618))
    figures.append(fig)

for i in range(1, 3):
    figures[n].x_range = figures[0].x_range

items = [slider] + combinations + word_length_divs + figures