Пример #1
0
def bokeh_histogram(x,
                    y,
                    pay_norm,
                    x_label: str,
                    y_label: str,
                    x_range: list,
                    title: str = '',
                    bc: str = "#f0f0f0",
                    bfc: str = "#fafafa"):

    bin_size = x[1] - x[0]

    s = bokeh_fig_init(x_range=x_range,
                       title=title,
                       x_label=x_label,
                       y_label=y_label,
                       bc=bc,
                       bfc=bfc)

    # Add copyright
    l1 = add_copyright()
    s.add_layout(l1)

    s.vbar(x=x,
           top=y,
           width=0.95 * bin_size,
           fill_color="#f8b739",
           fill_alpha=0.5,
           line_color=None)
    if CURRENCY_NORM and pay_norm == 1:
        s.xaxis[0].formatter = PrintfTickFormatter(format="$%ik")
    else:
        s.xaxis[0].formatter = PrintfTickFormatter(format="$%i")
    st.bokeh_chart(s, use_container_width=True)
Пример #2
0
def csd_base_figure(add_legend=True, add_custom_hover=True):
    """ function to make a CSD plot dummy"""
    fig = figure(width=800, height=600, sizing_mode='scale_both',
                 tools=['pan', 'box_zoom', 'reset', 'save', 'crosshair'],
                 toolbar_location='right', x_axis_type="log",
                 y_axis_type="linear", x_axis_label='time[s]',
                 y_axis_label='abundance')
    # fig.y_range = Range1d(1E-3, 1)
    fig.title.text = 'CSD Evolution'  # diagram name
    fig.title.align = 'left'  # setting layout
    fig.title.text_font_size = "14pt"
    fig.xaxis.axis_label_text_font_size = "16pt"
    fig.yaxis.axis_label_text_font_size = "16pt"
    fig.yaxis.major_label_text_font_size = "14pt"
    fig.xaxis.major_label_text_font_size = "14pt"
    fig.xaxis[0].formatter = PrintfTickFormatter(format="%4.1e")
    custom_hover = HoverTool()
    custom_hover.tooltips = """
        <style>
            .bk-tooltip>div:not(:first-child) {display:none;}
        </style>

        <b>time [s] </b> @x <br>
        <b>Relative abundance: </b> @y
    """
    if add_custom_hover:
        fig.add_tools(custom_hover)

    if add_legend:
        legend = Legend(items=[])
        fig.add_layout(legend)
        # fig.legend.title = 'charge states'
        fig.legend.location = "top_left"  # setup plot legend
        fig.legend.click_policy = "mute"
    return fig
Пример #3
0
def cs_base_figure():
    """ function to make a CS plot dummy"""
    fig = figure(width=800, height=600, sizing_mode='scale_both',
                 tools=['pan', 'box_zoom', 'reset', 'save', 'crosshair'],
                 toolbar_location='right', x_axis_type="linear",
                 y_axis_type="log", x_axis_label='charge state',
                 y_axis_label='reaction cross sections, cm²')
    fig.title.text = 'Processes cross sections, cm²'  # diagram name
    fig.title.align = 'left'  # setting layout
    fig.title.text_font_size = "14pt"
    fig.xaxis.axis_label_text_font_size = "16pt"
    fig.yaxis.axis_label_text_font_size = "16pt"
    fig.yaxis.major_label_text_font_size = "14pt"
    fig.xaxis.major_label_text_font_size = "14pt"
    fig.yaxis[0].formatter = PrintfTickFormatter(format="%4.1e")

    custom_hover = HoverTool()
    custom_hover.tooltips = """
        <style>
            .bk-tooltip>div:not(:first-child) {display:none;}
        </style>

        <b>charge state: </b> @x <br>
        <b>process rate: </b> @y
    """
    fig.add_tools(custom_hover)
    legend = Legend(items=[])
    fig.add_layout(legend)
    fig.legend.location = "top_right"  # setup plot legend
    fig.legend.click_policy = "mute"
    return fig
Пример #4
0
    def create_map_plot(self):
        lat = 39.8282
        lng = -98.5795
        zoom = 6
        xr = Range1d()
        yr = Range1d()
        x_range = xr
        y_range = yr
        #map_options = GMapOptions(lat=39.8282, lng=-98.5795, zoom=6)
        map_options = GMapOptions(lat=lat, lng=lng, zoom=zoom)
        #map_options = GMapOptions(lat=30.2861, lng=-97.7394, zoom=15)
        plot = GMapPlot(x_range=x_range,
                        y_range=y_range,
                        map_options=map_options,
                        plot_width=680,
                        plot_height=600,
                        title=" ")
        plot.map_options.map_type = "hybrid"
        xaxis = LinearAxis(axis_label="lon",
                           major_tick_in=0,
                           formatter=NumeralTickFormatter(format="0.000"))
        plot.add_layout(xaxis, 'below')
        yaxis = LinearAxis(axis_label="lat",
                           major_tick_in=0,
                           formatter=PrintfTickFormatter(format="%.3f"))
        plot.add_layout(yaxis, 'left')

        self.plot = plot
Пример #5
0
def make_lin():
    #Create figure object.
    p = figure(title='Lin. Plot of COVID-19 ' + plot_title[sel_var] + ' (' +
               txt_src + ')',
               toolbar_location='above',
               plot_height=250,
               plot_width=500,
               x_axis_type='datetime',
               tools='pan, wheel_zoom, box_zoom, reset',
               sizing_mode="scale_width")

    # Format your x-axis as datetime.
    p.xaxis[0].formatter = DatetimeTickFormatter(days='%b %d')
    p.yaxis[0].formatter = PrintfTickFormatter(format='%.1e')

    p.circle(x='Date',
             y='Selected',
             source=source_grp,
             fill_color='Color',
             line_color='Color',
             legend_field='Country')

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

    p.add_layout(dt_span)

    # Add your tooltips
    p.add_tools(hover)
    return p
    def make_plot(src):


        p1 = figure(title="Gasverbruik per uur",
                   x_range=(-0.5,23.5), y_range=(-0.5,6.5),
                   x_axis_location="above", plot_width=900, plot_height=400,
                   tools=TOOLS, toolbar_location='below',
                   tooltips=[('Verbruik', '@aantal'),('Dag', '@dayofweek'),('Uur','@hour')]
                  )

        p1.grid.grid_line_color = None
        p1.axis.axis_line_color = None
        p1.axis.major_tick_line_color = None
        p1.axis.major_label_text_font_size = "5pt"
        p1.axis.major_label_standoff = 0
        p1.xaxis.major_label_orientation = pi / 3
        p1.xaxis.ticker = FixedTicker(ticks=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23])
        p1.yaxis.ticker = FixedTicker(ticks=[0,1,2,3,4,5,6])
        p1.yaxis.major_label_overrides = {0:'Maandag', 1:'Dinsdag', 2:'Woensdag', 3:'Donderdag', 4:'Vrijdag', 5:'Zaterdag', 6:'Zondag'}
        
        p1.rect(x="hour", y="dayofweek", width=1, height=1,
               source=src,
               fill_color={'field': 'aantal', 'transform': mapper1},
               line_color=None)
        
        color_bar1 = ColorBar(color_mapper=mapper1, major_label_text_font_size="5pt",
                             ticker=BasicTicker(desired_num_ticks=len(colors)),
                             formatter=PrintfTickFormatter(format="%d"),
                             label_standoff=6, border_line_color=None, location=(0, 0))
        p1.add_layout(color_bar1, 'right')
        
        return p1
Пример #7
0
def make_plot():
    # prepare data stuff - take the keys from the data in order of likelihood
    categories = list(reversed(probly.keys()))
    palette = [cc.rainbow[i * 15] for i in range(17)]
    x = linspace(-20, 110, 500)
    source = ColumnDataSource(data=dict(x=x))

    p = figure(y_range=categories, plot_width=900, x_range=(-5, 105), toolbar_location=None)

    for i, cat in enumerate(reversed(categories)):
        pdf = gaussian_kde(probly[cat])
        y = ridge(cat, pdf(x))
        source.add(y, cat)
        p.patch('x', cat, color=palette[i], alpha=0.6, line_color="black", source=source)

    p.outline_line_color = None
    p.background_fill_color = "#efefef"

    p.xaxis.ticker = FixedTicker(ticks=list(range(0, 101, 10)))
    p.xaxis.formatter = PrintfTickFormatter(format="%d%%")

    p.ygrid.grid_line_color = None
    p.xgrid.grid_line_color = "#dddddd"
    p.xgrid.ticker = p.xaxis[0].ticker

    p.axis.minor_tick_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.axis_line_color = None

    p.y_range.range_padding = 0.12

    return p
Пример #8
0
def bokeh_scatter_init(pay_norm: int,
                       x_label: str,
                       y_label: str,
                       title: str = '',
                       x_range: list = None,
                       bc: str = "#f0f0f0",
                       bfc: str = "#fafafa",
                       plot_constants: bool = False) -> figure:

    x_buffer = 1000 / pay_norm
    x_min = 10000 / pay_norm
    x_limit = 500000 / pay_norm
    if CURRENCY_NORM and pay_norm == 1:
        x_buffer /= 1e3
        x_min /= 1e3
        x_limit /= 1e3

    if pay_norm != 1:
        x_label = 'Hourly Rate'

    if x_range is None:
        x_range = [x_min - x_buffer, x_limit + x_buffer]

    s = bokeh_fig_init(x_range=x_range,
                       title=title,
                       x_label=x_label,
                       y_label=y_label,
                       bc=bc,
                       bfc=bfc,
                       tools="pan,wheel_zoom,box_zoom,hover,save,reset",
                       active_scroll='wheel_zoom',
                       tooltips=TOOLTIPS)

    constants_level = [2500, 5000, 10000, 15000, 20000]

    if CURRENCY_NORM and pay_norm == 1:
        s.xaxis[0].formatter = PrintfTickFormatter(format="$%ik")
    else:
        if pay_norm > 1:
            s.xaxis[0].formatter = PrintfTickFormatter(format="$%i")
        else:
            s.xaxis[0].formatter = PrintfTickFormatter(format="$%i")

    if plot_constants:
        s = draw_constant_salary_bump(s, constants_level, pay_norm)

    return s
Пример #9
0
def plot_map(perf_map, res, title='performance map', colors=BLUE_COLORS, show=True, scale='default'):
    ps = list(perf_map.values())
    p_min, p_max = np.min(ps), np.max(ps)
    if scale == 'log':
        c_min, c_max = -math.log(-p_min+EPSILON), -math.log(-p_max+EPSILON)
    else:
        c_min, c_max = p_min, p_max

    img = np.zeros((res, res), dtype=np.uint32)
    view = img.view(dtype=np.uint8).reshape(img.shape + (4,))

    for (i, j), p in perf_map.items():
        if scale == 'log':
            p = -math.log(-p+EPSILON)
        c_idx = int(np.floor((len(colors)-1)*(p - c_min)/(c_max-c_min)))
        r, g, b = colors[c_idx]
        view[j, i, 0] = r
        view[j, i, 1] = g
        view[j, i, 2] = b
        view[j, i, 3] = 255

    plot = bkp.figure(width=SIZE, height=SIZE, x_range=(-0.7, 0.7), y_range=(-0.7, 0.7),
                           title=title, tools = "pan,box_zoom,reset,save")
    plot.title.text_font_size = '12pt'
    plot.image_rgba([img], x=[-0.7],  y=[-0.7], dh=[1.4], dw=[1.4])

    if scale == 'log':
        cbar = colorbar(colors, inversed=True)
        cb_plot = bkp.figure(width=100, height=SIZE, x_range=(0, 1.0), y_axis_type="log", y_range=(-p_max, -p_min))
        cb_plot.image_rgba([cbar], x=[0.0],  y=[-p_max], dw=[1.0], dh=[p_max-p_min])
    else:
        cbar = colorbar(colors)
        cb_plot = bkp.figure(width=100, height=SIZE, x_range=(0, 1.0), y_range=(p_min, p_max))
        cb_plot.image_rgba([cbar], x=[0.0],  y=[p_min], dw=[1.0], dh=[p_max-p_min])

    cb_plot.min_border_right = 25
    cb_plot.xgrid.grid_line_color = None
    cb_plot.xaxis.minor_tick_line_color = None
    cb_plot.xaxis.major_tick_line_color = None
    cb_plot.xaxis.axis_line_color = None
    cb_plot.xaxis[0].formatter = PrintfTickFormatter(format="")
    if scale == 'log':
        cb_plot.yaxis.formatter = PrintfTickFormatter(format="-%1.0e")

    if show:
        bkp.show(bkp.gridplot([[plot, cb_plot]]))
    return [plot, cb_plot]
Пример #10
0
def draw_book(df, params):
    asks = df["ask"].dropna()
    bids = df["bid"].dropna()
    p = figure(plot_width=book_params['size']['width'],
               plot_height=book_params['size']['height'],
               title=book_params["title"] +
               "\t\tBid : %1.8f \tAsk : %1.8f\tSpread : %1.8f" %
               (bids.index[-1], asks.index[0], asks.index[0] - bids.index[-1]))
    p.toolbar.logo = None
    p.toolbar_location = None
    p.title.text_color = "whitesmoke"
    p.title.text_font = "noto"
    p.background_fill_color = "#36393e"
    p.border_fill_color = "#36393e"
    p.grid.grid_line_color = "whitesmoke"
    p.grid.grid_line_alpha = 0.4
    p.grid.minor_grid_line_color = "whitesmoke"
    p.grid.minor_grid_line_alpha = 0.2
    p.outline_line_color = "whitesmoke"
    p.outline_line_alpha = 0.3
    p.xaxis.formatter = PrintfTickFormatter(format=params['tickFormat'])
    p.yaxis.formatter = PrintfTickFormatter(format="%f")
    p.axis.major_tick_line_color = "whitesmoke"
    p.axis.minor_tick_line_color = "whitesmoke"
    p.axis.axis_line_color = "whitesmoke"
    p.axis.major_label_text_color = "whitesmoke"
    p.axis.major_label_text_font = "noto"
    p.axis.major_label_text_font_size = "10pt"
    p.x_range = Range1d(bids.index.min(), asks.index.max())
    p.y_range = Range1d(0, max(bids.max(), asks.max()))
    p.patch(np.append(np.array(asks.index),
                      [np.array(asks.index).max(),
                       np.array(asks.index).min()]),
            np.append(asks.values, [0, 0]),
            alpha=0.7,
            line_width=2,
            color=book_params["colors"]["ask"])
    p.patch(np.append(np.array(bids.index),
                      [np.array(bids.index).max(),
                       np.array(bids.index).min()]),
            np.append(bids.values, [0, 0]),
            alpha=0.7,
            line_width=2,
            color=book_params["colors"]["bid"])
    return p
Пример #11
0
def make_plot(name, wave_list, spec_list, color_list, label_list, image,
              sx, sy):
    plot = figure(plot_height=300, plot_width=800,
               toolbar_location=None, x_axis_location="above",
               background_fill_color="#efefef", x_range=(3470., 5540.),
               y_axis_type="linear")

    imageplot = figure(plot_height=540, plot_width=430,
                       tools="crosshair, pan, reset, save, wheel_zoom",
                       y_axis_location="right",
                       tooltips=[("x", "$x"), ("y", "$y"),
                                 ("value", "@image")],
                       x_range=(image[1].min(), image[1].max()),
                       y_range=(image[2].min(), image[2].max()))

    select = figure(title=("Drag the selection "
                           "box to change the range above"),
                    plot_height=240, plot_width=800, y_range=plot.y_range,
                    y_axis_type="linear",
                    tools="", toolbar_location=None,
                    background_fill_color="#efefef")
    for wavelength, spectrum, color, label in zip(wave_list, spec_list, 
                                                  color_list, label_list):               
        source = ColumnDataSource(data=dict(wavelength=wavelength, 
                                            spectrum=spectrum))
        plot.line('wavelength', 'spectrum', source=source, line_width=3,
                  line_alpha=0.6, line_color=color,
                  legend=label)
        select.line('wavelength', 'spectrum', source=source,
                    line_color=color)
    plot.yaxis.axis_label = '1e-17 ergs/s/cm^2/A'
    for p in [plot, select]:
        p.xaxis.major_label_text_font_size = "14pt"
        p.yaxis.major_label_text_font_size = "14pt"
        p.xaxis.axis_label = 'Wavelength'
        p.xaxis.axis_label_text_font_size = "16pt"
        p.yaxis.axis_label_text_font_size = "16pt"
        p.xaxis.major_tick_line_color = "firebrick"
        p.xaxis.major_tick_line_width = 3
        p.xaxis.minor_tick_line_color = "orange"
        p.yaxis.major_tick_line_color = "firebrick"
        p.yaxis.major_tick_line_width = 3
        p.yaxis.minor_tick_line_color = "orange"
        p.yaxis[0].formatter = PrintfTickFormatter(format="%3.1f")
    select.ygrid.grid_line_color = None
    range_tool = RangeTool(x_range=plot.x_range)
    range_tool.overlay.fill_color = "navy"
    range_tool.overlay.fill_alpha = 0.2
    select.add_tools(range_tool)
    select.toolbar.active_multi = range_tool
    imageplot.image(image=[image[0]], x=image[1].min(), y=image[2].min(),
                    dw=image[1].max()-image[1].min(),
                    dh=image[2].max()-image[2].min())
    imageplot.scatter(sx, sy, marker='circle_x', size=15,
              line_color="orange", fill_color="red", alpha=0.75)
    output_file(name+".html", title=name)
    save(row(column(plot, select), imageplot))
Пример #12
0
def make_heatmap_object(df, years, months):
    ''' makes a bokeh figure '''
    # this is the colormap from the original NYTimes plot
    colors = [
        "#75968f", "#a5bab7", "#c9d9d3", "#e2e2e2", "#dfccce", "#ddb7b1",
        "#cc7878", "#933b41", "#550b1d"
    ]
    mapper = LinearColorMapper(palette=colors,
                               low=df.rate.min(),
                               high=df.rate.max())

    source = ColumnDataSource(df)

    TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"

    # p is a bokeh figure object
    p = figure(title="US Unemployment ({0} - {1})".format(years[0], years[-1]),
               x_range=years,
               y_range=list(reversed(months)),
               x_axis_location="above",
               plot_width=900,
               plot_height=400,
               tools=TOOLS,
               toolbar_location='below')

    p.grid.grid_line_color = None
    p.axis.axis_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.major_label_text_font_size = "5pt"
    p.axis.major_label_standoff = 0
    p.xaxis.major_label_orientation = pi / 3

    p.rect(x="Year",
           y="Month",
           width=1,
           height=1,
           source=source,
           fill_color={
               'field': 'rate',
               'transform': mapper
           },
           line_color=None)

    color_bar = ColorBar(color_mapper=mapper,
                         major_label_text_font_size="5pt",
                         ticker=BasicTicker(desired_num_ticks=len(colors)),
                         formatter=PrintfTickFormatter(format="%d%%"),
                         label_standoff=6,
                         border_line_color=None,
                         location=(0, 0))
    p.add_layout(color_bar, 'right')

    p.select_one(HoverTool).tooltips = [
        ('date', '@Month @Year'),
        ('rate', '@rate%'),
    ]
    return p
Пример #13
0
    def _plot_wcorr(Wcorr, L):

        f = figure(tools="box_select, pan, reset, save")
        f.plot_width = 700
        f.plot_height = 600

        # Background settings
        f.background_fill_color = '#859dcd'
        f.background_fill_alpha = 0.05

        # Title settings
        f.title.text = "W-Correlation for L={}".format(L)
        f.title.text_font = 'Helvetica'
        f.title.text_font_size = '24px'
        f.title.align = 'center'
        f.title.text_font_style = "italic"

        # Axis settings
        f.xaxis.axis_label = 'Fⱼ'
        f.yaxis.axis_label = 'Fᵢ'
        f.axis.axis_label_text_font = 'Helvetica'
        f.axis.axis_label_text_font_size = '24px'
        f.axis.major_label_orientation = 0
        f.x_range = Range1d(start=0.5, end=L + 0.5)
        f.y_range = Range1d(start=L + 0.5, end=0.5)
        f.axis[0].ticker.desired_num_ticks = L
        f.axis[0].ticker.num_minor_ticks = 0

        data = DataFrame(Wcorr)
        axis = [i for i in range(1, Wcorr.shape[0] + 1)]

        data['F_i'] = axis
        data.set_index('F_i', inplace=True)

        data.columns = axis
        data.columns.name = 'F_j'
        df = DataFrame(data.stack(), columns=['corr']).reset_index()
        source = ColumnDataSource(df)

        # this is the colormap from the original NYTimes plot

        mapper = LinearColorMapper(palette=color.palettes['colors_2'], low=0, high=1)

        f.rect(x="F_i", y="F_j", width=1, height=1, source=source,
               line_color=None, fill_color=transform('corr', mapper))

        color_bar = ColorBar(color_mapper=mapper, location=(0, 0),
                             ticker=BasicTicker(desired_num_ticks=len(color.palettes['colors_2'])),
                             formatter=PrintfTickFormatter(format="%.2f"))

        f.add_layout(color_bar, 'right')

        hover = HoverTool(tooltips=[("Components", "(@F_i, @F_j)"),
                                    ("Correlations", "@corr")])
        f.add_tools(hover)

        show(f)
Пример #14
0
def make_heatmap_object(df, sample_lst, gene_lst):
    ''' makes a bokeh figure '''
    colors = [
        "#75968f", "#a5bab7", "#c9d9d3", "#e2e2e2", "#dfccce", "#ddb7b1",
        "#cc7878", "#933b41", "#550b1d"
    ]
    mapper = LinearColorMapper(palette=colors,
                               low=df['counts'].min(),
                               high=df['counts'].max())

    source = ColumnDataSource(df)

    TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"

    # p is a bokeh figure object
    p = figure(title="Gene Expression",
               x_range=sample_lst,
               y_range=gene_lst,
               x_axis_location="above",
               plot_width=600,
               plot_height=900,
               tools=TOOLS,
               toolbar_location='below')

    p.grid.grid_line_color = None
    p.axis.axis_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.major_label_text_font_size = "5pt"
    p.axis.major_label_standoff = 0
    p.xaxis.major_label_orientation = pi / 3

    p.rect(x="Samples",
           y="Gene_ID",
           width=1,
           height=1,
           source=source,
           fill_color={
               'field': 'counts',
               'transform': mapper
           },
           line_color=None)

    color_bar = ColorBar(color_mapper=mapper,
                         major_label_text_font_size="5pt",
                         ticker=BasicTicker(desired_num_ticks=len(colors)),
                         formatter=PrintfTickFormatter(format="%d"),
                         label_standoff=6,
                         border_line_color=None,
                         location=(0, 0))
    p.add_layout(color_bar, 'right')

    p.select_one(HoverTool).tooltips = [
        ('coord', '@Samples @Gene_ID'),
        ('count', '@counts'),
    ]
    return p
Пример #15
0
    def get_heatmap(cls):
        palette = palettes.Magma256
        mapper = LinearColorMapper(palette=palette, low=0, high=1)
        tools = "hover"
        xy_range = list(Data.res_df.index)

        # plot
        hm = figure(
            title="Heatmap",
            tools=tools,
            toolbar_location=None,
            x_range=xy_range,
            y_range=xy_range,
            plot_width=PAGE_WIDTH // 2 - 50
        )

        src = ColumnDataSource(Data.hm_df)
        hm.rect(
            x="uid_x",  # this needs to be column from DF
            y="uid_y",
            width=1,
            height=1,
            source=src,
            fill_color={'field': 'similarity', 'transform': mapper},  # mapper gives the coloring
            line_color='white'
        )

        hm.xaxis.major_label_orientation = 3.14 / 3  # rotation is in radians

        # color bar
        color_bar = ColorBar(
            color_mapper=mapper,
            major_label_text_font_size="8pt",
            ticker=BasicTicker(desired_num_ticks=10),
            formatter=PrintfTickFormatter(format="%0.1f"),
            label_standoff=10,
            border_line_color=None,
            location=(0, 0)
        )
        hm.add_layout(color_bar, 'right')

        hm.select_one(HoverTool).tooltips = App.format_tooltip_fields([
            ('Similarity', '@similarity'),
            ('X', '@uid_x'),
            ('Y', '@uid_y'),

            ('Survey X', '@survey_id_x (@survey_name_x)'),
            ('Form type X', '@form_type_x'),
            ('Tr. code X', '@tr_code_x'),

            ('Survey Y', '@survey_id_y (@survey_name_y)'),
            ('Form type Y', '@form_type_y'),
            ('Tr. code Y', '@tr_code_y'),
        ])

        return components(hm)
Пример #16
0
def plot_heatmap(data):
    index = list(data.index)
    columns = list(data.columns)

    import pandas as pd
    # reshape to 1D array or rates with a month and year for each row.
    df = pd.DataFrame(data.stack(), columns=['rate']).reset_index()

    # this is the colormap from the original NYTimes plot
    colors = [
        "#75968f", "#a5bab7", "#c9d9d3", "#e2e2e2", "#dfccce", "#ddb7b1",
        "#cc7878", "#933b41", "#550b1d"
    ]
    mapper = LinearColorMapper(palette=colors,
                               low=df.rate.min(),
                               high=df.rate.max())

    TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"

    p = figure(title="",
               x_range=list(reversed(columns)),
               y_range=index,
               x_axis_location="above",
               plot_width=550,
               plot_height=390,
               tools=TOOLS,
               toolbar_location='below',
               tooltips=[('date', '@columns @index'), ('rate', '@rate%')])

    p.grid.grid_line_color = None
    p.axis.axis_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.major_label_standoff = 0
    p.xaxis.major_label_orientation = math.pi / 3

    p.rect(x="columns",
           y="index",
           width=1,
           height=1,
           source=df,
           fill_color={
               'field': 'rate',
               'transform': mapper
           },
           line_color=None)

    color_bar = ColorBar(color_mapper=mapper,
                         major_label_text_font_size="7px",
                         ticker=BasicTicker(desired_num_ticks=len(colors)),
                         formatter=PrintfTickFormatter(format="%d%%"),
                         label_standoff=6,
                         border_line_color=None,
                         location=(0, 0))
    p.add_layout(color_bar, 'right')
    script, div = components(p)
    return script, div
Пример #17
0
    def mat(self, output_name, nodesX, nodesY, counts):

        xname = []
        yname = []

        for node1 in nodesX:
            for node2 in nodesY:
                xname.append(node1)
                yname.append(node2)

        source = ColumnDataSource(data=dict(
            xnames=xname,
            ynames=yname,
            count=counts.flatten(),
        ))


        colors = ["#FFFFFF", "#CCCCFF", "#9999FF", "#5555FF", "#0000FF", "#0000CC", "#0000AA", "#000088", "#000000"]

        exp_cmap = LogColorMapper(palette=colors, low = 0, high = 10)
        # exp_cmap = LogColorMapper(palette=colors, low = np.min(counts), high = np.max(counts))

        p = figure(title="Matrix Figure",
                   x_axis_location="above", tools="hover,save",
                   x_range=nodesX, y_range=list(reversed(nodesY)))

        p.rect(x='xnames', y='ynames', width=0.9, height=0.9,
               source=source, line_color=None, fill_color=transform('count', exp_cmap))

        p.plot_width = 800
        p.plot_height = 800
        p.grid.grid_line_color = None
        p.axis.axis_line_color = None
        p.axis.major_tick_line_color = None
        p.axis.major_label_text_font_size = "5pt"
        p.axis.major_label_standoff = 0
        p.xaxis.major_label_orientation = np.pi / 3

        #圖例
        color_bar = ColorBar(color_mapper=exp_cmap, location=(0, 0),
                             ticker=BasicTicker(desired_num_ticks=len(colors)), 
                             formatter=PrintfTickFormatter(format="%d"))

        p.add_layout(color_bar, 'right')

        #游標所指“點”的說明格式
        p.select_one(HoverTool).tooltips = [
            ('names', '@ynames -> @xnames'),
            ('count', '@count'),
        ]

        output_file(output_name + ".html", title=output_name)
        
        show(p)  # show the plot
Пример #18
0
    def get_logloss_graph(self, n_every=1000, n_ave=10):
        steps, ll = self.get_log_data('step', 'logloss', n_every)
        ave_ll = self.get_average(ll, n_ave)
        
        dct = {'title': 'Logloss', 
               'x': {'data': steps}, 
               'y': {'data': ll, 'color': '#fed6e5'},  # Light pink
               'ave y': {'data': ave_ll, 'color': '#FD367E'},  # Pink
               'x axis': {'label': 'steps', 'formatter': NumeralTickFormatter(format='0,000')},
               'y axis': {'label': 'logloss', 'formatter': PrintfTickFormatter(format='%.3f')}}              

        return self.get_graph(dct)
Пример #19
0
def _setup_glyph_coloring(_, color_high=0.3):

    # colors = list(reversed(bokeh.palettes.Greens[9]))

    mapper = LinearColorMapper(palette=COLORS, low=0.0, high=color_high)
    color_transform = bokeh.transform.transform('weight', mapper)
    color_bar = ColorBar(
        color_mapper=mapper,
        location=(0, 0),
        ticker=BasicTicker(desired_num_ticks=len(COLORS)),
        formatter=PrintfTickFormatter(format=" %5.2f"),
    )
    return color_transform, color_bar
Пример #20
0
def contourfPlot(Radar_var, name, minmax=None, steps=100, colormap="jet"):
    # ========== get Colors =====================
    if minmax == None:
        max_dbz = np.nanmax(Radar_var)
        min_dbz = np.nanmin(Radar_var)
    else:
        min_dbz, max_dbz = minmax

    rangeGateHeight = Radar.range()[2] - Radar.range()[1]
    rgb = getColormapAsList(steps, colormap)

    # ========== prepare data for plotting ==============
    df = pd.DataFrame(Radar_var, index=Radar.time(), columns=Radar.range())
    df.columns.name = "range"
    df.index.name = "time"
    df1 = pd.DataFrame(df.stack(), columns=['data']).reset_index()

    source = ColumnDataSource(df1)

    mapper = LinearColorMapper(palette=rgb, low=min_dbz, high=max_dbz)
    # ====================================

    cf = p1.rect(x="time",
                 y="range",
                 height=rangeGateHeight,
                 width=timedelta(seconds=time_resolution),
                 source=source,
                 fill_color={
                     'field': 'data',
                     'transform': mapper
                 },
                 legend=name)
    cf.glyph.line_color = cf.glyph.fill_color
    cf.glyph.line_color = None

    contourlist.append(cf)
    p1.plot_width = 1300
    p1.plot_height = 1000
    p1.sizing_mode = "scale_width"

    # Colorbar:
    color_bar = ColorBar(
        color_mapper=mapper,
        major_label_text_font_size="10pt",
        ticker=BasicTicker(desired_num_ticks=int(len(rgb) / 2)),
        formatter=PrintfTickFormatter(format="%d"),
        label_standoff=6,
        border_line_color=None,
        location=(0, 0))
    colorbarlist.append(color_bar)
Пример #21
0
def plotMap(infileName, plot_title, dot_size, col_type, bounds):
    #1. get list of X, Y, P values from dataframe
    dX, dY, dP = file2Dataframe('main/sold-price-data.txt')

    #2 assign colors to each P value using colorRange
    colors = colorRange(dP)

    #3 prepare for the plot, some tools can be removed
    TOOLS = 'hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,tap,save,box_select,poly_select,lasso_select,'
    p = figure(title=plot_title, tools=TOOLS)
    p.title.align = "center"
    p.grid.grid_line_color = 'black'
    p.axis.axis_line_color = 'black'
    p.axis.major_tick_line_color = 'black'
    p.axis.major_label_text_font_size = '10pt'

    # 4 draw dots with color coresponding to the P value in X, and Y coordinates.
    p.circle(x=dX, y=dY, size=dot_size, color=colors, line_color=None)

    # 5 mapping color bar color same with the plot and fix the ticker boundaries.
    palette_c = ["yellow"] * 5 + ["pink"] * 20 + ["red"] * 50 + [
        "green"
    ] * 20 + ["cyan"] * 5
    #Then this palette could be used with a LinearColorMapper with low, high = (0, 100).
    mapper = LinearColorMapper(palette=palette_c, low=dP.min(), high=dP.max())

    ticker = FixedTicker(ticks=bounds)

    color_bar = ColorBar(color_mapper=mapper,
                         major_label_text_font_size='5pt',
                         ticker=ticker,
                         formatter=PrintfTickFormatter(format='%d%%'),
                         label_standoff=6,
                         border_line_color=None,
                         location=(0, 0))

    # 6 give title to color bar
    color_bar_p = figure(title='price %',
                         title_location="right",
                         width=110,
                         toolbar_location=None,
                         outline_line_color=None)

    color_bar_p.add_layout(color_bar, 'right')
    color_bar_p.title.align = "center"
    layout = row(p, color_bar_p)

    # 6 output the component of the plot to web
    return components(layout)
Пример #22
0
    def draw_class_count_bar_chart(self):

        def check_for_undefined_classes():
            obs_class_nums = [c.replace('class', '') for c in source.data['index']]
            for ocn in obs_class_nums:
                if ocn not in self.las_classes:
                    self.las_classes.update({ocn: 'UNDEFINED'})


        self.class_counts['Expected'] = np.zeros(self.class_counts.index.size)
        self.class_counts['Unexpected'] = np.zeros(self.class_counts.index.size)
        for i, class_name in enumerate(self.class_counts.index):
            class_num = int(class_name.replace('class', ''))
            if class_num in self.config.exp_cls_key:
                self.class_counts['Expected'][i] = self.class_counts['counts'][i]
            else:
                self.class_counts['Unexpected'][i] = self.class_counts['counts'][i]

        source = ColumnDataSource(self.class_counts)
        check_for_undefined_classes()
        source.data.update({'labels': ['{} (Class {})'.format(
            self.las_classes[c.replace('class', '').zfill(2)], 
            c.replace('class', '').zfill(2)) for c in source.data['index']]})

        p2 = figure(y_range=source.data['labels'], plot_width=400, plot_height=400, 
                    title="Class Counts", tools="")
        p2.min_border_top = 100
        p2.outline_line_color = None
        p2.toolbar.logo = None
        p2.toolbar_location = None
        p2.xaxis[0].formatter = PrintfTickFormatter(format='%4.1e')

        p2_expected = p2.hbar(y='labels', right='Expected', 
                                height=0.9, color='#0074D9', source=source)

        p2_unexpected = p2.hbar(y='labels', right='Unexpected', 
                                height=0.9, color='#FF851B', source=source)

        max_count = max(source.data['counts'])
        self.class_counts = self.class_counts.drop(['counts'], axis=1)
        p2.x_range = Range1d(0, max_count + 0.1 * max_count)
        p2.xgrid.grid_line_color = None
        p2.xaxis.major_label_orientation = "vertical"
        p2.xaxis.minor_tick_line_color = None

        legend = Legend(items=[('EXPECTED', [p2_expected]), ('UNEXPECTED', [p2_unexpected])], location=(0, 10))
        p2.add_layout(legend, 'above')

        return p2
Пример #23
0
def create_color_mapper(palette: Sequence[str]) -> Tuple[LinearColorMapper, ColorBar]:
    """
    Create a color mapper and a colorbar for heatmap
    """
    mapper = LinearColorMapper(palette=palette, low=-1, high=1)
    colorbar = ColorBar(
        color_mapper=mapper,
        major_label_text_font_size="8pt",
        ticker=BasicTicker(),
        formatter=PrintfTickFormatter(format="%.2f"),
        label_standoff=6,
        border_line_color=None,
        location=(0, 0),
    )
    return mapper, colorbar
Пример #24
0
    def colorbar(self, mapper, title='(Val - Ref)'):
        formatter = PrintfTickFormatter(format="%4.2f")

        color_bar = ColorBar(color_mapper=mapper,
                             label_standoff=16,
                             title=title,
                             major_label_text_font_style='bold',
                             padding=26,
                             major_label_text_align='left',
                             major_label_text_font_size="10pt",
                             formatter=formatter,
                             title_text_baseline='alphabetic',
                             location=(0, 0))
        self.plot.add_layout(color_bar, 'right')
        return self
Пример #25
0
    def create_map_plot(self):
        lat = 39.8282
        lng = -98.5795
        zoom = 6
        xr = Range1d()
        yr = Range1d()
        x_range = xr
        y_range = yr
        #map_options = GMapOptions(lat=39.8282, lng=-98.5795, zoom=6)
        map_options = GMapOptions(lat=lat, lng=lng, zoom=zoom)
        #map_options = GMapOptions(lat=30.2861, lng=-97.7394, zoom=15)
        plot = GMapPlot(x_range=x_range,
                        y_range=y_range,
                        map_options=map_options,
                        title="Hotel Review Explorer",
                        plot_width=680,
                        plot_height=600)
        plot.map_options.map_type = "hybrid"
        xaxis = LinearAxis(axis_label="lon",
                           major_tick_in=0,
                           formatter=NumeralTickFormatter(format="0.000"))
        plot.add_layout(xaxis, 'below')
        yaxis = LinearAxis(axis_label="lat",
                           major_tick_in=0,
                           formatter=PrintfTickFormatter(format="%.3f"))
        plot.add_layout(yaxis, 'left')

        #pan = PanTool()
        #wheel_zoom = WheelZoomTool()
        #box_select = BoxSelectTool()
        #box_select.renderers = [rndr]
        #tooltips = "@name"
        #tooltips = "<span class='tooltip-text'>@names</span>\n<br>"
        #tooltips += "<span class='tooltip-text'>Reviews: @num_reviews</span>"
        #hover = HoverTool(tooltips="@num_reviews")
        #hover = HoverTool(tooltips="@names")
        #hover = HoverTool(tooltips=tooltips)
        #tap = TapTool()
        #plot.add_tools(pan, wheel_zoom, box_select, hover, tap)
        #plot.add_tools(hover, tap)
        #overlay = BoxSelectionOverlay(tool=box_select)
        #plot.add_layout(overlay)
        #plot.add_glyph(self.source, circle)
        #county_xs, county_ys = get_some_counties()
        #apatch = Patch(x=county_xs, y=county_ys, fill_color=['white']*len(county_xs))
        #plot.add_glyph(apatch)
        self.plot = plot
Пример #26
0
def plot_centairo_sentiment(data):
    x = np.linspace(0, 100, 100)
    source = ColumnDataSource(data=dict(x=x))
    categories = [x for x in data.keys()]
    values = [y for y in data.values()]
    p = figure(y_range=categories,
               plot_width=800,
               plot_height=300,
               x_range=(0, 101),
               toolbar_location=None,
               title="Centairo Sentiment and Emotion Results")
    p.square(values, categories, size=20, color="#b3de69")
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = "#000000"
    p.xaxis.formatter = PrintfTickFormatter(format="%d%%")
    p.xaxis.axis_label = "Confidence Score"
    return p
Пример #27
0
def colorce():
    import colorcet as cc
    from numpy import linspace
    from scipy.stats.kde import gaussian_kde

    from bokeh.io import output_file, show
    from bokeh.models import ColumnDataSource, FixedTicker, PrintfTickFormatter
    from bokeh.plotting import figure
    from bokeh.sampledata.perceptions import probly

    def ridge(category, data, scale=20):
        return list(zip([category]*len(data), scale*data))

    cats = list(reversed(probly.keys()))

    palette = [cc.rainbow[i*15] for i in range(17)]

    x = linspace(-20,110, 500)

    source = ColumnDataSource(data=dict(x=x))

    p = figure(y_range=cats, plot_width=900, x_range=(-5, 105), toolbar_location=None)

    for i, cat in enumerate(reversed(cats)):
        pdf = gaussian_kde(probly[cat])
        y = ridge(cat, pdf(x))
        source.add(y, cat)
        p.patch('x', cat, color=palette[i], alpha=0.6, line_color="black", source=source)

    p.outline_line_color = None
    p.background_fill_color = "#efefef"

    p.xaxis.ticker = FixedTicker(ticks=list(range(0, 101, 10)))
    p.xaxis.formatter = PrintfTickFormatter(format="%d%%")

    p.ygrid.grid_line_color = None
    p.xgrid.grid_line_color = "#dddddd"
    p.xgrid.ticker = p.xaxis.ticker

    p.axis.minor_tick_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.axis_line_color = None

    p.y_range.range_padding = 0.12
    return p
Пример #28
0
def plot_heatmap(params):
    params = np.array(params)
    trainer1 = params[..., 0, :]
    trainer2 = params[..., 1, :]

    N = 500
    x = np.linspace(0, 1, N)
    y = np.linspace(0, 1, N)
    xx, yy = np.meshgrid(x, y)
    d = 1.2 - xx**2 - yy**2

    mapper = LinearColorMapper(palette='Viridis256', low=-0.5, high=1.2)

    p = figure(x_range=(0, 1),
               y_range=(0, 1),
               tooltips=[("theta_x", "$x"), ("theta_y", "$y"),
                         ("value", "@image")])
    p.xaxis.axis_label = 'theta_x'
    p.yaxis.axis_label = 'theta_y'
    # must give a vector of image data for image parameter
    p.image(image=[d], x=0, y=0, dw=1., dh=1., palette='Viridis256')

    levels = np.linspace(-0.5, 1.2, 12)
    color_bar = ColorBar(color_mapper=mapper,
                         major_label_text_font_size="8pt",
                         ticker=FixedTicker(ticks=levels),
                         formatter=PrintfTickFormatter(format='%.2f'),
                         label_standoff=6,
                         border_line_color=None,
                         location=(0, 0))

    p.circle(trainer1[..., 0],
             trainer1[..., 1],
             size=2,
             color="black",
             alpha=0.5)
    p.circle(trainer2[..., 0],
             trainer2[..., 1],
             size=2,
             color="red",
             alpha=0.5)
    p.add_layout(color_bar, 'right')

    # show(p)
    return p
Пример #29
0
def Render_dashboard():
    # df_temp = pd.read_csv('BitBucketDashboardInput.csv')

    df1 =df_temp.groupby(['author']).size().reset_index().rename(index=str,columns={0:'commits'}).sort_values(by=['commits'], ascending=False).head(10)

    p1 = figure(x_range=list(df1['author']), plot_width=1200, plot_height=400, title="Top Committers of the Month",
               toolbar_location=None, tools="")

    p1.vbar(x=list(df1['author']), top=df1['commits'], width=0.9, color='#2171b5')

    p1.xgrid.grid_line_color = None
    p1.y_range.start = 0
    p1.axis.major_label_text_font_size = "10pt"

    print(df_temp.columns)
    df2 =df_temp.groupby(['author','month-date']).size().reset_index().rename(index=str,columns={0:'commits'})
    source = ColumnDataSource(df2)
    colors = list(reversed(['#084594', '#2171b5', '#4292c6', '#6baed6', '#9ecae1', '#c6dbef']))
    mapper = LinearColorMapper(palette=colors, low=df2.commits.min(), high=df2.commits.max())

    p2 = figure(plot_width=1200, plot_height=400, title="Author Commits by Day",
               x_range=sorted(list(df2['month-date'].unique())), y_range=sorted(list(df2['author'].unique())),
               toolbar_location=None, tools="", x_axis_location="above")

    p2.rect(x="month-date", y="author", width=1, height=1, source=source, line_color=None, fill_color=transform('commits', mapper))

    color_bar = ColorBar(color_mapper=mapper, location=(0, 0),
                         ticker=BasicTicker(desired_num_ticks=len(colors)),
                         formatter=PrintfTickFormatter(format="%d"))

    p2.add_layout(color_bar, 'right')

    p2.axis.axis_line_color = None
    p2.axis.major_tick_line_color = None
    p2.axis.major_label_text_font_size = "10pt"
    p2.axis.major_label_standoff = 0
    p2.xaxis.major_label_orientation = 1.0

    l = layout([[p1],[p2]], sizing_mode='stretch_both')

    html = file_html(l , CDN, "dashboard.html")

    Html_file= open("templates/dashboard.html","w")
    Html_file.write(html)
    Html_file.close()
Пример #30
0
    def _settings(self, title, provinces):
        """
        This function creates the scatter plot of the PCA analysis results. It loads data per province to split the
        colors. The line colors are used to indicate province, with the inside colors showing the relative amounts of
        deaths per 100.000 people per province. Range of the plot was set to get space for the legend.
        :param title: Data frame containing the principal components and the provinces
        :param provinces: The provinces used in the analysis to be added to the legend after plotting.
        :return: returns the PCA scatter plot.
        """
        plot = figure(plot_width=700, plot_height=550,
                      title=title,  x_range=(-7, 5))

        plot.xaxis.axis_label = "Principal Component 1"
        plot.yaxis.axis_label = "Principal Component 2"
        listofsources = []
        dict_of_provinces = {"Groningen": "PV20  ", "Friesland": "PV21  ", "Drenthe": "PV22  ", "Overijssel": "PV23  ",
                             "Flevoland": "PV24  ", "Gelderland": "PV25  ", "Utrecht": "PV26  ",
                             "Noord-Holland": "PV27  ",
                             "Zuid-Holland": "PV28  ", "Zeeland": "PV29  ", "Noord-Brabant": "PV30  ",
                             "Limburg": "PV31  "}
        for province in provinces:
            listofsources.append(ColumnDataSource(self.data_frame[self.data_frame['RegioS'] == dict_of_provinces[province]]))

        mapper = LinearColorMapper(
            palette='Greys256',
            low=self.data_frame["TotaalAlleOnderliggendeDoodsoorzaken_1"].min(),
            high=self.data_frame["TotaalAlleOnderliggendeDoodsoorzaken_1"].max()
        )
        size = 10

        for source, count in zip(listofsources, range(0, len(listofsources))):
            plot.circle(x='principal component 1', y='principal component 2',
                        size=size,
                        source=source, line_color=Category20b[12][count], line_width=3,
                        fill_color=transform('TotaalAlleOnderliggendeDoodsoorzaken_1', mapper), fill_alpha=1.0,
                        legend_label=provinces[count])

        color_bar = ColorBar(color_mapper=mapper, location=(0, 0),
                             ticker=BasicTicker(desired_num_ticks=10),
                             formatter=PrintfTickFormatter(format="%d"))

        plot.add_layout(color_bar, 'right')
        plot.legend.location = 'top_left'
        return plot