Beispiel #1
0
def _get_provincial_map(
    plot_width, source, tibet_source, legend_data, fill_color,
    line_color='black', line_width=0.5, tooltip_text=''
):
    p_map = get_map_plot(plot_width)
    provinces = Patches(
        xs='xs',
        ys='ys',
        fill_color=fill_color,
        line_color=line_color,
        line_width=line_width,
        line_join='round',
    )
    pr = p_map.add_glyph(source, provinces)
    tibet = Patches(
        xs='xs',
        ys='ys',
        fill_color='white',
        line_color='gray',
        line_dash='dashed',
        line_width=0.5,
    )
    tr = p_map.add_glyph(tibet_source, tibet)

    # Add legend
    legend_source = ColumnDataSource(legend_data)
    rect = Rect(
        x='x',
        y=map_legend_y,
        height=1,
        width=0.3,
        fill_color='color',
        line_color=None,
    )
    p_map.add_glyph(legend_source, rect)
    # Add start val
    text_start = [legend_data.vals[0][:-2]]
    p_map.add_glyph(
        ColumnDataSource(
            dict(x=[map_legend_x], y=[map_legend_y - 3.5], text=text_start)
        ), Text(x='x', y='y', text='text', text_font_size='7pt', text_align='left')
    )
    # Add end val
    text_end = [legend_data.vals[99][:-2]]  # Note the 99 is dependent on legend having 100 points
    if len(text_end[0]) > 5:
        text_end = [legend_data.vals[99][0:5]]
    p_map.add_glyph(
        ColumnDataSource(
            dict(x=[map_legend_x + 25], y=[map_legend_y - 3.5], text=text_end)
        ), Text(x='x', y='y', text='text', text_font_size='8pt', text_align='right')
    )

    # Add hovers
    tooltips = "<span class='tooltip-text'>@name_en</span>"
    tooltips = tooltips + "<span class='tooltip-text'>%s</span>" % tooltip_text
    p_map.add_tools(HoverTool(tooltips=tooltips, renderers=[pr]))
    tibet_tooltips = "<span class='tooltip-text'>@name_en (No data)</span>"
    p_map.add_tools(HoverTool(tooltips=tibet_tooltips, renderers=[tr]))

    return p_map
Beispiel #2
0
def construct_key(palette):
    xdr = Range1d(0, 250)
    ydr = Range1d(0, 50)

    plot = Plot(x_range=xdr,
                y_range=ydr,
                title="",
                plot_width=250,
                plot_height=50,
                min_border=0,
                **PLOT_FORMATS)

    for index, color in enumerate(palette):
        width = 19
        rect = Rect(x=((width * index) + 40),
                    y=40,
                    width=width,
                    height=10,
                    fill_color=color,
                    line_color='white')
        plot.add_glyph(rect)

    zero = Text(x=30, y=15, text=['0 %'], **FONT_PROPS_SM)
    hundred = Text(x=190, y=15, text=['100 %'], **FONT_PROPS_SM)
    plot.add_glyph(zero)
    plot.add_glyph(hundred)

    return plot
Beispiel #3
0
    def __init__(self, *args, **kwargs):
        super(RPCWidget, self).__init__(*args, **kwargs)

        self.python_calls = Text(text='')

        self.js_calls = Text(text='')

        self.python_calls.on_change('text', self.python_call)

        self._registered_functions = {}
Beispiel #4
0
    def create_legend(self):

        x_range = Range1d(0, 185)
        y_range = Range1d(0, 130)

        text_box = Plot(x_range=x_range,
                        y_range=y_range,
                        title="",
                        plot_width=185,
                        plot_height=130,
                        min_border=0,
                        **PLOT_FORMATS)

        FONT_PROPS_SM['text_font_size'] = '11pt'
        text_box.add_glyph(
            Text(x=35, y=9, text=['Low Average Rating'], **FONT_PROPS_SM))
        text_box.add_glyph(
            Rect(x=18,
                 y=18,
                 width=25,
                 height=25,
                 fill_color='#ef4e4d',
                 line_color=None))
        text_box.add_glyph(
            Text(x=35, y=49, text=['Medium Average Rating'], **FONT_PROPS_SM))
        text_box.add_glyph(
            Rect(x=18,
                 y=58,
                 width=25,
                 height=25,
                 fill_color='#14a1af',
                 line_color=None))

        text_box.add_glyph(
            Text(x=35, y=89, text=['High Average Rating'], **FONT_PROPS_SM))
        text_box.add_glyph(
            Rect(x=18,
                 y=98,
                 width=25,
                 height=25,
                 fill_color='#743184',
                 line_color=None))

        self.legend_plot = text_box

        ##Filler plot
        x_range = Range1d(0, 40)
        y_range = Range1d(0, 100)
        self.legend_filler = Plot(x_range=x_range,
                                  y_range=y_range,
                                  title="",
                                  plot_width=40,
                                  plot_height=100,
                                  min_border=0,
                                  **PLOT_FORMATS)
Beispiel #5
0
def africa_map_add_legend(palette, africa_map_plot_width):
    """This creates the colormap legend under the map of Africa.

    Input:
        palette: Defines colormap to use in legend
        africa_map_plot_width: Width of map plot used for scaling/positioning

    Credit:
    Adds glyphs for legend. Based on [1]

    References:
        [1] https://github.com/chdoig/scipy2015-blaze-bokeh/blob/master
            /1.5%20Glyphs%20-%20Legend%20(solution).ipynb
    """
    # Set ranges
    xdr = Range1d(0, africa_map_plot_width)
    ydr = Range1d(0, 60)

    # Create plot
    legend = Plot(
        x_range=xdr,
        y_range=ydr,
        plot_width=africa_map_plot_width,
        plot_height=60,
        min_border=0,
        toolbar_location=None,
        outline_line_color="#FFFFFF",
    )

    # Add the legend color boxes and text
    width = 40
    height = 20
    for i, color in enumerate(palette):
        rect = Rect(x=(width * (i + 1)),
                    y=40,
                    width=width * 1,
                    height=height,
                    fill_color=color,
                    line_color='black')
        legend.add_glyph(rect)

    tick_min = Text(x=width / 2, y=0, text=['0'])
    legend.add_glyph(tick_min)
    text_scale = Text(x=width * 3, y=0, text=['Logarithmic scale'])
    legend.add_glyph(text_scale)
    tick_max = Text(x=width * (len(palette)), y=0, text='tick_max')

    legend.add_glyph(colormap_legend_cds, tick_max)

    return legend
Beispiel #6
0
def make_phase_plot(data):
    G = make_graph(data)
    layout = nx.nx_agraph.graphviz_layout(G, prog="twopi", root="root")
    (x_lim, y_lim) = get_limits(layout)

    p = figure(x_range=x_lim, y_range=y_lim)

    graph = from_networkx(G, layout, center=(0,0))
    graph.node_renderer.glyph = Circle(size="size", fill_color="white", line_color="white")
    graph.edge_renderer.glyph = MultiLine(line_color="black", line_alpha=0.5, line_width=1)
    graph.name="base_graph"
    p.renderers.append(graph)

    graph2 = from_networkx(G, layout, center=(0,0))
    graph2.node_renderer.glyph = Circle(size="size", fill_color="color", fill_alpha=0.5, line_color="color")
    graph2.edge_renderer.visible=False
    graph2.name="nodes"
    p.renderers.append(graph2)

    graph3 = from_networkx(G, layout, center=(0,0))
    graph3.node_renderer.glyph = Text(text="name", text_align="center", text_baseline="middle", text_font_size="9pt")
    graph3.edge_renderer.visible=False
    graph3.name="labels"
    p.renderers.append(graph3)

    p.tools = []
    p.toolbar.logo = None
    p.xaxis.visible = False
    p.yaxis.visible = False
    p.xgrid.visible = False
    p.ygrid.visible = False

    return p
Beispiel #7
0
    def build_legend(network, grouped_colors, grouped_legend):
        legend = dict()

        for group_color, color in grouped_colors.items():
            for group_label, label in grouped_legend.items():
                if group_color == group_label:
                    legend[label] = color

        x_pos_text = 0.6
        y_pos_text = 1.9

        x_pos_color = 0.5
        y_pos_color = 1.94

        for label, color in legend.items():
            network.add_glyph(
                Text(x=x_pos_text,
                     y=y_pos_text,
                     text=[label],
                     text_font_size='10pt',
                     text_color='#666666'))
            y_pos_text = y_pos_text - 0.1

            network.add_glyph(
                Circle(x=x_pos_color,
                       y=y_pos_color,
                       fill_color=[color][0],
                       line_color=None,
                       fill_alpha=0.8,
                       size=10))
            y_pos_color = y_pos_color - 0.1

        return network
Beispiel #8
0
def plot_text_data(data, unit, name, color):
    xdr = Range1d(start=-1, end=1)
    ydr = Range1d(start=-1, end=1)
    texts = []
    plt = figure(x_range=xdr, y_range=ydr, plot_width=300, plot_height=300)
    plt.outline_line_color = None


    #img_path = join(dirname(__file__), 'static','images','wcu.png')
    #img_path = join('E:','Git', 'formulaufsm_dataSoftware', 'static', 'images', 'wcu.png')
    #print(img_path)
    #image  = ImageURL(url=[img_path], x=0, y=0, w=2, global_alpha=.1, angle=0, angle_units = 'deg', anchor="center")
    #plt.add_glyph(image)

    for i in range(0,len(name)):
        texts.append(Text(x=-1+0.5, y=-0.2*i+0.5, text=[name[i] +': ' + str(data[i]) + unit[i]], text_color=color[i], text_align="left", text_baseline="top", text_font_style="bold"))
        plt.add_glyph(texts[i])

    plt.toolbar.logo = None
    plt.toolbar_location = None
    plt.xaxis.visible = False
    plt.yaxis.visible = False
    plt.xgrid.grid_line_color = None
    plt.ygrid.grid_line_color = None

    return plt, texts
Beispiel #9
0
def empty_plot(plot_dim, title, scale, scale_text=1):

    p = figure(plot_height=plot_dim[0],
               plot_width=plot_dim[1],
               x_range=(1, 10),
               y_range=(1, 10),
               title=title)

    p = USAID_style(p)

    font_size = str(20 * scale * scale_text) + 'pt'
    source = ColumnDataSource({'x': [4], 'y': [5], 'text': ['No Data']})
    glyph = Text(x="x",
                 y="y",
                 text="text",
                 text_color='#999999',
                 text_font='Gill Sans MT',
                 text_font_size=font_size)

    p.add_glyph(source, glyph)

    p.axis.major_label_text_color = 'white'
    p.toolbar.logo = None
    p.toolbar_location = None

    return p
Beispiel #10
0
def add_text(plot, *, text: str, **kwargs):
    from bokeh.models import Text
    # ugh. for f**k's sake, Label doesn't support multiline... https://github.com/bokeh/bokeh/issues/7317
    # and glyphs always want a data source
    textsrc = CDS({'text': [text]})
    kwargs['text'] = 'text'
    glyph = Text(**kwargs)
    plot.add_glyph(textsrc, glyph)
Beispiel #11
0
def make_lightcurve_figure_elements(lc, model_lc, lc_source, model_lc_source, help_source):
    """Make a figure with a simple light curve scatter and model light curve line.

    Parameters
    ----------
    lc : lightkurve.LightCurve
        Light curve to plot
    model_lc :  lightkurve.LightCurve
        Model light curve to plot
    lc_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for plotting light curve
    model_lc_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for plotting model light curve
    help_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for rendering help button

    Returns
    -------
    fig : bokeh.plotting.figure
        Bokeh figure object
    """
    # Make figure
    fig = figure(title='Light Curve', plot_height=300, plot_width=900,
                 tools="pan,box_zoom,reset",
                 toolbar_location="below",
                 border_fill_color="#FFFFFF", active_drag="box_zoom")
    fig.title.offset = -10
    fig.yaxis.axis_label = 'Flux (e/s)'
    if lc.time_format == 'bkjd':
        fig.xaxis.axis_label = 'Time - 2454833 (days)'
    elif lc.time_format == 'btjd':
        fig.xaxis.axis_label = 'Time - 2457000 (days)'
    else:
        fig.xaxis.axis_label = 'Time (days)'
    ylims = [np.nanmin(lc.flux), np.nanmax(lc.flux)]
    fig.y_range = Range1d(start=ylims[0], end=ylims[1])

    # Add light curve
    fig.circle('time', 'flux', line_width=1, color='#191919',
               source=lc_source, nonselection_line_color='#191919', size=0.5,
               nonselection_line_alpha=1.0)
    # Add model
    fig.step('time', 'flux', line_width=1, color='firebrick',
             source=model_lc_source, nonselection_line_color='firebrick',
             nonselection_line_alpha=1.0)

    # Help button
    question_mark = Text(x="time", y="flux", text="helpme", text_color="grey",
                         text_align='center', text_baseline="middle",
                         text_font_size='12px', text_font_style='bold',
                         text_alpha=0.6)
    fig.add_glyph(help_source, question_mark)
    help = fig.circle('time', 'flux', alpha=0.0, size=15, source=help_source,
                      line_width=2, line_color='grey', line_alpha=0.6)
    tooltips = help_source.data['help'][0]
    fig.add_tools(HoverTool(tooltips=tooltips, renderers=[help],
                            mode='mouse', point_policy="snap_to_data"))
    return fig
Beispiel #12
0
    def make_legend_plot(self, min_idx=0, max_idx=MAX_IDX):
        x_range = Range1d(0, 90)
        y_range = Range1d(0, 295)
        x_range = Range1d(0, 580)
        y_range = Range1d(0, 30)

        text_box = Plot(x_range=x_range,
                        y_range=y_range,
                        title="",
                        plot_width=580,
                        plot_height=30,
                        min_border=0,
                        **PLOT_FORMATS)

        prices_aves = [
            "67 ", "185", "271", "367", "500", "685", "827", "989", "1242",
            "1354", "1611"
        ]

        text_box.add_glyph(Text(x=2, y=1, text=['Ave:'], **FONT_PROPS_SMALLER))
        text_box.add_glyph(
            Text(x=24, y=1, text=['$' + prices_aves[0]], **FONT_PROPS_SMALLER))
        text_box.add_glyph(
            Rect(x=33,
                 y=22,
                 width=23,
                 height=10,
                 fill_color=Spectral11[0],
                 line_color=None))

        for i in range(1, 11):
            text_box.add_glyph(
                Text(x=(21 + 52 * i),
                     y=1,
                     text=['$' + prices_aves[i]],
                     **FONT_PROPS_SMALLER))
            text_box.add_glyph(
                Rect(x=33 + 52 * i,
                     y=22,
                     width=23,
                     height=10,
                     fill_color=Spectral11[i],
                     line_color=None))

        self.legend_plot = text_box
def add_text():
    N = 9
    x = [1]
    y = [1]
    text = [str(random.randint(0, N))]
    source = ColumnDataSource(dict(x=x, y=y, text=text))
    glyph = Text(x="x", y="y", text="text", text_font_size="200px", text_align="center", text_baseline="middle", angle=0, text_color="#96deb3")
    plot.add_glyph(source, glyph)
    print("Printed " + str(text[0]))
Beispiel #14
0
    def create_legend(self):
        x_range = Range1d(0, 550)
        y_range = Range1d(0, 38)

        text_box = Plot(x_range=x_range,
                        y_range=y_range,
                        title="",
                        plot_width=680,
                        plot_height=38,
                        min_border=0,
                        **PLOT_FORMATS)

        text_box.add_glyph(
            Text(x=47, y=15, text=['High Average Rating'], **FONT_PROPS_SM))
        text_box.add_glyph(
            Text(x=423, y=15, text=['Low Average Rating'], **FONT_PROPS_SM))
        text_box.add_glyph(
            Text(x=235, y=15, text=['Medium Average Rating'], **FONT_PROPS_SM))

        #GREEN
        text_box.add_glyph(
            Rect(x=25,
                 y=20,
                 width=25,
                 height=25,
                 fill_color="#41ab5d",
                 line_color=None))
        #YELLOW
        text_box.add_glyph(
            Rect(x=217,
                 y=20,
                 width=25,
                 height=25,
                 fill_color="#ffffbf",
                 line_color=None))
        #RED
        text_box.add_glyph(
            Rect(x=402,
                 y=20,
                 width=25,
                 height=25,
                 fill_color="#e31a1c",
                 line_color=None))
        self.legend_plot = text_box
def add_text(plot):
    plot = add_axes(plot)
    # Add the year in background (add before circle)
    text = Text(x=2,
                y=35,
                text='year',
                text_font_size='150pt',
                text_color='#EEEEEE')
    plot.add_glyph(text_source, text)
    return plot
Beispiel #16
0
def plotGauge(speedvalue, offset = 0,
              name = '', unit = '', color = '', maxValue = 0,
              major_step = 2, minor_step = .5):
    '''
    draw a gauge for show online data
    :param speedvalue: data value for a especific channel
    :param offset: offset is the minimum value of the channel
    :param name: name of the channel
    :param unit: units of the data value
    :param color: color of the gauge
    :param maxValue: max value of the chaneel
    :param major_step: step for points inside the gauge
    :param minor_step: step for points inside the gauge
    :return: figure plot in bokeh engine
    '''

    maxValue = maxValue - offset
    xdr = Range1d(start=-1.25, end=1.25)
    ydr = Range1d(start=-1.25, end=1.25)

    renderer = 'webgl'
    plt = Plot(x_range=xdr, y_range=ydr, plot_width=300, plot_height=300, output_backend=renderer,)
    plt.toolbar_location = None
    plt.outline_line_color = None

    plt.add_glyph(Circle(x=0, y=0, radius=1.00, fill_color="white", line_color="black"))
    plt.add_glyph(Circle(x=0, y=0, radius=0.05, fill_color="gray", line_color="black"))

    plt.add_glyph(Text(x=0, y=+0.15, text=[unit], text_color=color, text_align="center", text_baseline="bottom",
                        text_font_style="bold"))

    plt.add_glyph(Text(x=0, y=-0.15, text=[name], text_color="black", text_align="center", text_baseline="top",
                        text_font_style="bold"))

    add_gauge(plt, 0.75, maxValue, 0.05, +1, color, major_step, minor_step, offset = offset)

    valueGliph = Text(x=0, y=-0.6, text=["0"], text_color=color, text_align="center", text_baseline="top")

    plt.add_glyph(valueGliph)

    a, b = add_needle(plt, speedvalue, offset = offset, max_value = maxValue)
    return plt, a, b, valueGliph
Beispiel #17
0
def make_folded_figure_elements(f, f_model_lc, f_source, f_model_lc_source, help_source):
    """Make a scatter plot of a FoldedLightCurve.

    Parameters
    ----------
    f : lightkurve.LightCurve
        Folded light curve to plot
    f_model_lc :  lightkurve.LightCurve
        Model folded light curve to plot
    f_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for plotting folded light curve
    f_model_lc_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for plotting model folded light curve
    help_source : bokeh.plotting.ColumnDataSource
        Bokeh style source object for rendering help button

    Returns
    -------
    fig : bokeh.plotting.figure
        Bokeh figure object
    """

    # Build Figure
    fig = figure(title='Folded Light Curve', plot_height=340, plot_width=450,
                 tools="pan,box_zoom,reset",
                 toolbar_location="below",
                 border_fill_color="#FFFFFF", active_drag="box_zoom")
    fig.title.offset = -10
    fig.yaxis.axis_label = 'Flux'
    fig.xaxis.axis_label = 'Phase'

    # Scatter point for data
    fig.circle('phase', 'flux', line_width=1, color='#191919',
               source=f_source, nonselection_line_color='#191919',
               nonselection_line_alpha=1.0, size=0.1)

    # Line plot for model
    fig.step('phase', 'flux', line_width=3, color='firebrick',
             source=f_model_lc_source, nonselection_line_color='firebrick',
             nonselection_line_alpha=1.0)

    # Help button
    question_mark = Text(x="phase", y="flux", text="helpme", text_color="grey",
                         text_align='center', text_baseline="middle",
                         text_font_size='12px', text_font_style='bold',
                         text_alpha=0.6)
    fig.add_glyph(help_source, question_mark)
    help = fig.circle('phase', 'flux', alpha=0.0, size=15, source=help_source,
                      line_width=2, line_color='grey', line_alpha=0.6)

    tooltips = help_source.data['help'][0]
    fig.add_tools(HoverTool(tooltips=tooltips, renderers=[help],
                            mode='mouse', point_policy="snap_to_data"))
    return fig
Beispiel #18
0
def DonutChartWithLegend(lab_dic,amt_dic,title):

    from bokeh.layouts import layout 
    from bokeh.models import ( 
      HoverTool, ColumnDataSource, Legend, LegendItem, Text
    ) 
    from bokeh.plotting import figure 
    from bokeh.palettes import brewer 
    from numpy import pi  
    
    for key,val in lab_dic.items():
        hv1 = key
        labels = val
        
    for key,val in amt_dic.items():
        hv2 = key
        amounts = val
    
    sangles,eangles = getStartsEnds(amounts)
    
    colors = getPartyColors(labels)    
     
    source=ColumnDataSource(dict(starts=sangles, ends=eangles,\
                                 labels=labels, amounts=amounts,colors=colors)) 

    plot =  figure(toolbar_location="right",min_border=20) 

    hover = HoverTool( 
            tooltips=[ 
              (hv1, '@labels'), 
              (hv2,'@amounts') 
            ] 
        ) 
    plot.add_tools(hover) 
    
    glyph=Text(text=[title],\
               text_align="center",text_baseline="middle",\
               text_color="#774422",text_font_style="bold",text_font_size="10pt")
    
    plot.add_glyph(glyph)

    r = plot.annular_wedge(0, 0, start_angle='starts', end_angle='ends',\
                           color='colors', inner_radius=0.7, outer_radius=0.8,\
                           source=source) 
  
    legend = Legend(items=[LegendItem(label=dict(field="labels"), \
                                      renderers=[r])], location=(0, 0)) 
    plot.add_layout(legend, 'right') 
    
    plot.axis.visible = False
    plot.grid.visible = False

    
    return plot, source
Beispiel #19
0
 def add_text_label_on_pie(p, df, label_name):
     source = ColumnDataSource(df.to_dict(orient='list'))
     txt = Text(
         x="text_x",
         y="text_y",
         text=label_name,
         angle="text_angle",
         text_align="center",
         text_baseline="middle",
         text_font_size='10pt',
     )
     p.add_glyph(source, txt)
Beispiel #20
0
def create_categorical_legend(colormap, aliases=None, font_size=10):
    '''
    Creates a bokeh plot object with circle legend
    swatches and text corresponding to the ``colormap`` key values
    or the optional aliases values.

    Parameters
    ----------
    colormap : dict
        Dictionary of category value to color value

    aliases : dict
        Dictionary of category value to aliases name

    font_size: int
        Font size to use in the legend text
    '''
    y_max = font_size * 2 * len(colormap)

    plot_options = {}
    plot_options['x_range'] = Range1d(start=0, end=200)
    plot_options['y_range'] = Range1d(start=0, end=y_max)
    plot_options['plot_height'] = y_max + 2 * font_size
    plot_options['plot_width'] = 190
    plot_options['min_border_bottom'] = 0
    plot_options['min_border_left'] = 0
    plot_options['min_border_right'] = 0
    plot_options['min_border_top'] = 0
    plot_options['outline_line_width'] = 0
    plot_options['toolbar_location'] = None

    legend = Plot(**plot_options)

    for i, (cat, color) in enumerate(colormap.items()):
        text_y = y_max - font_size / 2 - i * font_size * 2
        text_val = aliases[cat] if aliases else cat
        legend.add_glyph(
            Text(x=40,
                 y=text_y - font_size * 1.2,
                 text=[text_val],
                 text_font_size='{}pt'.format(font_size),
                 text_color='#666666'))

        legend.add_glyph(
            Circle(x=15,
                   y=text_y - font_size / 2,
                   fill_color=color,
                   size=font_size,
                   line_color=None,
                   fill_alpha=0.8))

    return legend
Beispiel #21
0
def matrix_heatmap(the_matrix):
    'Create a bokeh graphic with matrix cells colored by value. Or use bokeh "heatmap".'
    # pandas 'stack' is equivalent to R reshape gather, or melt from reshape2, from wide to long format. 
    # Prepare data.frame in the right format
    # the_matrix.drop(['F', 'sup'], axis=1, inplace=True)
    # the_matrix.columns=  the_matrix.index
    df = the_matrix.stack().rename("value").reset_index()

    #  The plot output:
    # output_file(ROOT_DIR / "cmPlot.html")

    # You can use your own palette here
    colors = brewer['YlGnBu'][9][1:9]

    # Had a specific mapper to map color with value
    mapper = LinearColorMapper(
        palette=colors, low=df.value.min(), high=df.value.max())
    # Define a figure
    p = figure(
        plot_width=800,
        plot_height=700,
        title="20 Newsgroups Confusion Matrix",
        y_range=list(df.level_0.drop_duplicates()),
        x_range=list(df.level_1.drop_duplicates()),
        toolbar_location=None,
        tools="",
        x_axis_location="above")

    df['cnt'] = df['value'].apply(str)
    cds = ColumnDataSource(df)
    # Create rectangle for heatmap
    p.rect(
        y="level_0",
        x="level_1",
        alpha = 0.4,
        width=1,
        height=1,
        source=cds,
        line_color=None,
        fill_color=transform('value', mapper))
    glyph = Text(y="level_0", x="level_1", text="cnt", x_offset= -10.0, y_offset=10.0, text_color="black")
    p.add_glyph(cds, glyph)

    #Add legend
    color_bar = ColorBar(
        color_mapper=mapper,
        location=(0,0),
        ticker=BasicTicker(desired_num_ticks=len(colors)))
    p.add_layout(color_bar, 'right')

    return p
Beispiel #22
0
    def __init__(self, shita, loan, months, ribit, madad, figures):
        self.fig1 = figures[0]
        self.fig2 = figures[1]
        self.loan = loan
        self.months = months
        self.ribit = ribit
        self.madad = madad
        self.shita_string = shita
        if self.shita_string == "keren" or self.shita_string == "keren_shava":
            self.shita = ks.keren_shava(loan, months, ribit)
        elif self.shita_string == "shpitzer":
            self.shita = shp.shpitzer(loan, months, ribit)
        else:
            raise KeyError("Error shita is no valid {}".format(shita))

        self.shita.build_table(loan, months, ribit)

        self.source_left_loan = ColumnDataSource(
            data=dict(x=range(0, self.months), y=self.shita.get_left_loan()))
        self.source_monthly_ret = ColumnDataSource(data=dict(
            x=range(0, self.months), y=self.shita.get_monthly_total()))

        self.fig1.circle(x='x',
                         y='y',
                         source=self.source_left_loan,
                         color=self.shita.color,
                         size=2,
                         alpha=0.3)
        self.fig2.circle(x='x',
                         y='y',
                         source=self.source_monthly_ret,
                         color=self.shita.color,
                         size=2,
                         alpha=0.3)
        text = [self.shita.get_monthly_total()[0]]
        if self.shita.color == 'green':
            x_text = 0
            y_text = 4200
        else:
            x_text = 0
            y_text = 3900
        self.source_text_monthly_ret = ColumnDataSource(
            dict(x=[x_text], y=[y_text], text=text))
        glyph = Text(x="x",
                     y="y",
                     text="text",
                     angle=0.0,
                     text_color=self.shita.color,
                     name='show_monthly_payment')
        self.fig2.add_glyph(self.source_text_monthly_ret, glyph)
Beispiel #23
0
def fetchProcessChart(data,cnts):

    bp = figure(plot_width=600, plot_height=300,y_axis_type="datetime",responsive=True,tools='')#,toolbar_location=None
    bp.toolbar.logo = None
    bp.toolbar_location = None

    bp.xaxis[0].formatter = NumeralTickFormatter(format="0.0%")
    bp.yaxis[0].formatter=FuncTickFormatter.from_py_func(hm)
    bp.xaxis[0].axis_label = '% of portals'
    bp.yaxis[0].axis_label = 'Time elapsed'

    mx=None
    c=0

    for sn in sorted(data.keys()):
        d=data[sn]

        d_sorted = np.sort(np.array(d))
        y=[e for e in d_sorted] #datetime.datetime.fromtimestamp(e)
        x = 1. * arange(len(d)) / (len(d) - 1)
        mx=max(x) if max(x)>mx else mx

        if sn == max(data.keys()):
            ci=bp.circle(x,y, size=5, alpha=0.5,  color='red', legend="current week: "+getWeekString(sn))
            li=bp.line(x,y, line_width=2,line_color='red', legend="current week: "+getWeekString(sn))
        else:
            ci=bp.circle(x,y, size=5, alpha=0.5,  color='gray')
            li=bp.line(x,y, line_width=2,line_color='gray')
            #hit_target =Circle(x,y, size=10,line_color=None, fill_color=None)


            #c.select(dict(type=HoverTool)).tooltips = {"Week": "@week",m:"@"+m.lower()}
            #hit_renderers.append(hit_renderer)

            bp.add_tools(HoverTool(renderers=[li], tooltips={"Week": getWeekString(sn)}))

        c+=1
        #bp.text(,y[-1], line_width=2,line_color=OrRd9[c],legend=str(sn))
        no_olympics_glyph = Text(x=x[-1], y=y[-1], x_offset=100, text=["%s of %s portals"%(len(d), cnts[sn])],
            text_align="right", text_baseline="top",
            text_font_size="9pt", text_font_style="italic", text_color="black")
        bp.add_glyph(no_olympics_glyph)

    bp.x_range=Range1d(0, mx*1.2)
    bp.background_fill_color = "#fafafa"

    bp.legend.location = "top_left"

    return bp
def tags_plot(df, plot_width=400, plot_height=400):
    graph_df = calculate_graph_coords(df, 'tag')
    graph_df["radius"] = normalize(graph_df.url, MAX_CIRCLE_SIZE, MIN_CIRCLE_SIZE)
    graph_df["label"] = graph_df.index.astype(str) + ' (' + graph_df.url.astype(str) + ')'
    graph_df["text_y"] = graph_df.y - graph_df.radius - 0.100 ## fudge factor

    source = ColumnDataSource(graph_df)

    line_coords = calculate_query_correlation(df, 'tag')

    # Create connection lines.
    lines = defaultdict(list)
    for k, v in line_coords.items():
        lines['xs'].append([graph_df.loc[k[0]]['x'], graph_df.loc[k[1]]['x']])
        lines['ys'].append([graph_df.loc[k[0]]['y'], graph_df.loc[k[1]]['y']])
        lines['line_width'].append(v*MAX_LINE_SIZE)

    line_source = ColumnDataSource(lines)

    if len(df) == 1:
        x_range = Range1d(0.2, 1.8)
        y_range = Range1d(-1.25, 1.25)
    else:
        x_range = Range1d(-1.25, 1.25)
        y_range = Range1d(-1.25, 1.25)

    NETWORK_FORMATS = PLOT_FORMATS.copy()
    NETWORK_FORMATS['toolbar_location'] = 'right'

    plot = Plot(title="Tags Network",
                plot_width=plot_width, plot_height=plot_height,
                x_range=x_range, y_range=y_range,
                **NETWORK_FORMATS)
    plot.add_glyph(
        line_source,
        MultiLine(xs="xs", ys="ys", line_width="line_width", line_color=Spectral4[1])
    )
    plot.add_glyph(
        source,
        Circle(x="x", y="y", radius="radius", fill_color=Spectral4[1], line_color=Spectral4[1])
    )
    plot.add_glyph(
        source,
        Text(x="x", y="text_y", text="label", text_baseline='middle',
            text_align="center", text_alpha=0.9, **FONT_PROPS_SM)
    )
    plot.add_tools(WheelZoomTool(), ResetTool(), PanTool())

    return plot
Beispiel #25
0
def _get_national_scenario_line_plot(sources, data, parameter=None, y_ticks=None, plot_width=600, grid=True, end_factor=None, y_range=None, include_bau=True):
    if not y_range:
        y_range = get_y_range(data)

    plot = Plot(
        x_range=get_year_range(end_factor),
        y_range=y_range,
        plot_width=plot_width,
        **PLOT_FORMATS
    )
    plot = add_axes(plot, y_ticks, color=dark_grey, grid=grid)
    hit_renderers = []
    line_renderers = {}
    if include_bau:
        sc = scenarios
    else:
        sc = scenarios_no_bau
    for scenario in sc:
        source = sources[scenario]
        line = Line(
            x='t', y=parameter, line_color=scenarios_colors[scenario],
            line_width=2, line_cap='round', line_join='round'
        )
        circle = Circle(
            x='t', y=parameter, size=4,
            line_color=scenarios_colors[scenario], line_width=0.5, line_alpha=deselected_alpha,
            fill_color=scenarios_colors[scenario], fill_alpha=0.6
        )
        # invisible circle used for hovering
        hit_target = Circle(
            x='t', y=parameter, size=20,
            line_color=None, fill_color=None
        )
        scenario_label = Text(
            x=value(source.data['t'][-1] + 0.8), y=value(source.data[parameter][-1] * 0.98), text=value(names[scenario]),
            text_color=scenarios_colors[scenario], text_font_size="8pt",
        )

        hit_renderer = plot.add_glyph(source, hit_target)
        hit_renderers.append(hit_renderer)
        line_renderer = plot.add_glyph(source, line)
        line_renderers[scenario] = line_renderer
        plot.add_glyph(source, circle)
        plot.add_glyph(scenario_label)

    plot.add_tools(HoverTool(tooltips="@%s{0,0} (@t)" % parameter, renderers=hit_renderers))
    return (plot, line_renderers)
    def __init__(self, image_views, sv_metadata, sv_streamctrl):
        """Initialize a intensity ROI overlay.

        Args:
            image_views (ImageView): Associated streamvis image view instances.
            sv_metadata (MetadataHandler): A metadata handler to report metadata issues.
            sv_streamctrl (StreamControl): A StreamControl instance of an application.
        """
        self._sv_metadata = sv_metadata
        self._sv_streamctrl = sv_streamctrl

        # ---- intensity ROIs
        self._source = ColumnDataSource(
            dict(left=[],
                 right=[],
                 bottom=[],
                 top=[],
                 text_x=[],
                 text_y=[],
                 text=[]))
        quad_glyph = Quad(
            left="left",
            right="right",
            bottom="bottom",
            top="top",
            fill_alpha=0,
            line_color="white",
        )

        text_glyph = Text(
            x="text_x",
            y="text_y",
            text="text",
            text_align="right",
            text_baseline="top",
            text_color="white",
        )

        for image_view in image_views:
            image_view.plot.add_glyph(self._source, quad_glyph)
            image_view.plot.add_glyph(self._source, text_glyph)

        # ---- toggle button
        toggle = CheckboxGroup(labels=["Intensity ROIs"], default_size=145)
        self.toggle = toggle
Beispiel #27
0
async def show_embedding(embedding: np.ndarray, targets: List[str], alg: str = ""):
    embedding = np.asarray(embedding)

    # scale each dimension between 0 and 1
    for dim in range(embedding.shape[1]):
        embedding[:, dim] = embedding[:, dim] - embedding[:, dim].min()
        embedding[:, dim] /= embedding[:, dim].max()
        embedding[:, dim] -= 0.5

    images = [
        k for k, target in enumerate(targets) if "img" in target or "video" in target
    ]
    image_urls = [image_url(target) for k, target in enumerate(targets) if k in images]

    data = {
        "x": embedding[images, 0],
        "y": embedding[images, 1] if len(embedding[0]) > 1 else embedding[images, 0],
        "image_url": image_urls,
    }
    source = ColumnDataSource(data=data)

    plot = figure(
        title=alg,
        plot_width=600,
        plot_height=500,
        toolbar_location="right",
        background_fill_color="#fafafa",
    )
    #  glyph = Text(x="x", y="y", text="text", angle=0.3, text_color="#96deb3")
    w = h = {"units": "data", "value": 0.1}
    w = h = {"units": "screen", "value": 80}
    glyph = ImageURL(x="x", y="y", url="image_url", w=w, h=h)
    plot.add_glyph(source, glyph)

    text = [k for k in range(len(targets)) if k not in images]
    data = {
        "x": embedding[text, 0],
        "y": embedding[text, 1] if len(embedding[0]) > 1 else embedding[text, 0],
        "text": [target for k, target in enumerate(targets) if k in text],
    }
    glyph = Text(x="x", y="y", text="text")
    source = ColumnDataSource(data=data)
    plot.add_glyph(source, glyph)
    return plot
def practice_slider():
    """ A simple practice slider for the webpage """
    slider = Slider(start=0,
                    end=10,
                    value=0,
                    step=0.25,
                    title='Current Value',
                    bar_color='black')
    source = ColumnDataSource(data=dict(
        x=[0.0], y=[0.0], txt=['Move Slider to 5.0'], color=['blue']))

    callback = CustomJS(args=dict(source=source, s=slider),
                        code="""
                        const data = source.data;
                        const txt = data['txt']
                        const col = data['color']
                        const s_val = s.value
                        
                        if (s_val == 5.0) {
                            txt[0] = 'Good Job!'
                            col[0] = 'green'
                        } else {
                            txt[0] = 'Move Slider to 5.0'
                            col[0] = 'blue'
                        }
                        source.change.emit();
                        """)
    plot1 = figure(plot_width=350,
                   plot_height=80,
                   x_range=[-1, 5],
                   y_range=[-1, 2],
                   tools="")

    txt = Text(x='x', y='y', text='txt', text_color='color')
    plot1.add_glyph(source, txt)

    slider.js_on_change('value', callback)
    plot1.toolbar_location = None
    plot1.axis.visible = False
    plot1.xgrid.grid_line_color = None
    plot1.ygrid.grid_line_color = None

    layout = column([plot1, slider])
    show(layout)
Beispiel #29
0
def get_pm25_national_plot(plot_width=600, end_factor=None, grid=True):
    sources, data = get_pm25_national_data()
    y_ticks = [30, 40, 50, 60, 70]
    y_range = Range1d(30, 72)
    pm25, line_renderers = _get_national_scenario_line_plot(
        sources, data, 'PM25_exposure',
        y_ticks=y_ticks, plot_width=plot_width, grid=grid, end_factor=end_factor, y_range=y_range
    )
    # Add Targets
    pm25.add_glyph(
        ColumnDataSource(data=dict(x=[2010, 2030], y=[35, 35])),
        Line(x='x', y='y', line_width=2, line_dash='dotdash'),
    )
    pm25.add_glyph(
        ColumnDataSource(data=dict(x=[2010.5], y=[32.5], text=['PM2.5 target'])),
        Text(x='x', y='y', text='text', text_font_size='8pt'),
        level='overlay',
    )
    return (pm25, line_renderers)
Beispiel #30
0
def create_text(text,
                text_color='grey',
                text_font_size='20px',
                fig_len=fig_len,
                fig_height=fig_height):
    fig = figure(plot_width=fig_len, plot_height=fig_height)
    text = Text(x=data['publishedAt'].min(),
                y=0,
                text=[text],
                text_color=text_color,
                text_font_size=text_font_size)
    fig.add_glyph(text)
    # decrease clutter
    fig.outline_line_color = None
    fig.xgrid.grid_line_color = None
    fig.ygrid.grid_line_color = None
    fig.yaxis.visible = False
    fig.xaxis.visible = False
    return fig