Пример #1
0
    def use_server_to_change_glyphs(self):
        source_original = ColumnDataSource(
            dict(average_grades=[7, 8, 10],
                 exam_grades=[6, 9, 8],
                 student_names=["Stephan", "Helder", "Riazudidn"]))

        source = ColumnDataSource(
            dict(average_grades=[7, 8, 10],
                 exam_grades=[6, 9, 8],
                 student_names=["Stephan", "Helder", "Riazudidn"]))

        # create the figure
        f = figure(x_range=Range1d(start=0, end=12),
                   y_range=Range1d(start=0, end=12))

        # add labels for glyphs
        labels = LabelSet(x="average_grades",
                          y="exam_grades",
                          text="student_names",
                          x_offset=5,
                          y_offset=5,
                          source=source)
        f.add_layout(labels)

        # create glyphs
        f.circle(x="average_grades", y="exam_grades", source=source, size=8)

        # create filtering function
        def filter_grades(attr, old, new):
            source.data = {
                key: [
                    value for i, value in enumerate(source_original.data[key])
                    if source_original.data["exam_grades"][i] >= slider.value
                ]
                for key in source_original.data
            }
            print(slider.value)

        # create label function
        def update_labels(attr, old, new):
            labels.text = select.value

        # create select widget
        options = [("average_grades", "Average Grades"),
                   ("exam_grades", "Exam Grades"),
                   ("student_names", "Student Names")]
        select = Select(title="Attribute", options=options)
        select.on_change("value", update_labels)

        slider = Slider(start=min(source_original.data["exam_grades"]) - 1,
                        end=max(source_original.data["exam_grades"]) + 1,
                        value=8,
                        step=0.1,
                        title="Exam Grade: ")
        slider.on_change("value", filter_grades)

        # create layout and add to curdoc
        lay_out = layout([[select], [slider]])
        curdoc().add_root(f)
        curdoc().add_root(lay_out)
Пример #2
0
def test_LabelSet():
    label_set = LabelSet()
    assert label_set.plot is None
    assert label_set.level == 'annotation'
    assert label_set.x is None
    assert label_set.y is None
    assert label_set.x_units == 'data'
    assert label_set.y_units == 'data'
    assert label_set.text == 'text'
    assert label_set.angle == 0
    assert label_set.angle_units == 'rad'
    assert label_set.x_offset == 0
    assert label_set.y_offset == 0
    assert label_set.render_mode == 'canvas'
    assert label_set.x_range_name == 'default'
    assert label_set.y_range_name == 'default'
    assert isinstance(label_set.source, ColumnDataSource)
    assert label_set.source.data == {}
    check_text_properties(label_set)
    check_fill_properties(label_set, "background_", None, 1.0)
    check_line_properties(label_set, "border_", None, 1.0, 1.0)
    check_properties_existence(label_set, [
        "plot", "visible", "level", "x", "y", "x_units", "y_units", "text",
        "angle", "angle_units", "x_offset", "y_offset", "render_mode",
        "x_range_name", "y_range_name", "source"
    ], TEXT, ANGLE, prefix('border_', LINE), prefix('background_', FILL))
Пример #3
0
    def select_label(self):
        source = ColumnDataSource(
            dict(average_grades=["B+", "A", "D-"],
                 exam_grades=["A+", "C", "D"],
                 student_names=["Stephan", "Helder", "Riazudidn"]))

        # create the figure
        f = figure(x_range=[
            "F", "D-", "D", "D+", "C-", "C", "C+", "B-", "B", "B+", "A-", "A",
            "A+"
        ],
                   y_range=[
                       "F", "D-", "D", "D+", "C-", "C", "C+", "B-", "B", "B+",
                       "A-", "A", "A+"
                   ])

        # add labels for glyphs
        labels = LabelSet(x="average_grades",
                          y="exam_grades",
                          text="student_names",
                          x_offset=5,
                          y_offset=5,
                          source=source)
        f.add_layout(labels)

        # create glyphs
        f.circle(x="average_grades", y="exam_grades", source=source, size=8)

        # create function
        def update_labels(attr, old, new):
            labels.text = select.value

        # create select widget
        options = [("average_grades", "Average Grades"),
                   ("exam_grades", "Exam Grades"),
                   ("student_names", "Student Names")]
        select = Select(title="Attribute", options=options)
        select.on_change("value", update_labels)

        # create layout and add to curdoc
        lay_out = layout([[select]])
        curdoc().add_root(f)
        curdoc().add_root(lay_out)
Пример #4
0
    def use_server_with_radio_buttons(self):
        # crate columndatasource
        source = ColumnDataSource(
            dict(average_grades=["B+", "A", "D-"],
                 exam_grades=["A+", "C", "D"],
                 student_names=["Stephan", "Helder", "Riazudidn"]))

        # create the figure
        f = figure(x_range=[
            "F", "D-", "D", "D+", "C-", "C", "C+", "B-", "B", "B+", "A-", "A",
            "A+"
        ],
                   y_range=[
                       "F", "D-", "D", "D+", "C-", "C", "C+", "B-", "B", "B+",
                       "A-", "A", "A+"
                   ])

        # add labels for glyphs
        labels = LabelSet(x="average_grades",
                          y="exam_grades",
                          text="student_names",
                          x_offset=5,
                          y_offset=5,
                          source=source)
        f.add_layout(labels)

        # create glyphs
        f.circle(x="average_grades", y="exam_grades", source=source, size=8)

        # create function
        def update_labels(attr, old, new):
            labels.text = options[radio_button_group.active]

        # create select widget
        options = ["average_grades", "exam_grades", "student_names"]
        radio_button_group = RadioButtonGroup(labels=options)
        radio_button_group.on_change("active", update_labels)

        # create layout and add to curdoc
        lay_out = layout([[radio_button_group]])
        curdoc().add_root(f)
        curdoc().add_root(lay_out)
Пример #5
0
def scatter(data,
            labels=None,
            title='scatter plot',
            showlabels=False,
            folder='',
            colors=None,
            xname='',
            yname="",
            importance=None,
            radi=5,
            alpha=0.8,
            **kwargs):
    """
    Makes an interactive scatter plot using Bokeh

    Args:
    -----
      data: array-like with shape [N,2]
      labels: list[str] a list of N names for each points
      title: str the plot title
      showlabels: bool if the labels should be always displayed or not (else just on hover)
      colors: list[int] of N integers from 0 up to 256 for the dot's colors
      folder: str of location where to save the plot, won't save if empty
      xname: str the name of the x axes
      yname: str the name of the y axes
      importance: a list[int] of N values to scale the size of the dots and their opacity by
      radi: int the size of the dots
      alpha: float the opacity of the dots
      **kwargs: additional bokeh.figure args

    Returns:
    ------
      the bokeh object
    """
    TOOLS = "hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,save,box_select,lasso_select,"

    col = viridis(len(set(colors))) if colors is not None else ['#29788E'
                                                                ]  # (viridis1)
    radii = []
    fill_alpha = []
    cols = []
    for i in range(data.shape[0]):
        radii.append(radi if importance is None else radi / 2 +
                     importance[i] * 30)
        fill_alpha.append(alpha if importance is None else alpha -
                          (0.2 * importance[i]))
        cols.append(col[0] if colors is None else col[int(colors[i])])
    source = ColumnDataSource(
        data=dict(x=data[:, 0],
                  y=data[:, 1],
                  labels=labels if labels is not None else [''] * len(radii),
                  fill_color=cols,
                  fill_alpha=fill_alpha,
                  radius=radii))
    TOOLTIPS = [
        ("name", "@labels"),
        ("(x,y)", "(@x, @y)"),
    ]
    p = figure(tools=TOOLS, tooltips=TOOLTIPS, title=title)
    p.circle('x',
             'y',
             color='fill_color',
             fill_alpha='fill_alpha',
             line_width=0,
             radius='radius' if radi else None,
             source=source)
    p.xaxis[0].axis_label = xname
    p.yaxis[0].axis_label = yname
    if showlabels:
        labels = LabelSet(x='x',
                          y='y',
                          text='labels',
                          level='glyph',
                          text_font_size='9pt',
                          x_offset=5,
                          y_offset=5,
                          source=source,
                          render_mode='canvas')
        p.add_layout(labels)
    p.output_backend = "svg"
    try:
        show(p)
    except:
        show(p)
    if folder:
        save(p, folder + title.replace(' ', "_") + "_scatter.html")
        export_svg(p,
                   filename=folder + title.replace(' ', "_") + "_scatter.svg")
    return p
Пример #6
0
def volcano(data,
            folder='',
            tohighlight=None,
            tooltips=[('gene', '@gene_id')],
            title="volcano plot",
            xlabel='log-fold change',
            ylabel='-log(Q)',
            maxvalue=100,
            searchbox=False,
            logfoldtohighlight=0.15,
            pvaltohighlight=0.1,
            showlabels=False):
    """
    Make an interactive volcano plot from Differential Expression analysis tools outputs

    Args:
    -----
      data: a df with rows genes and cols [log2FoldChange, pvalue, gene_id]
      folder: str of location where to save the plot, won't save if empty
      tohighlight: list[str] of genes to highlight in the plot
      tooltips: list[tuples(str,str)] if user wants tot specify another bokeh tooltip
      title: str plot title
      xlabel: str if user wants to specify the title of the x axis
      ylabel: str if user wants tot specify the title of the y axis
      maxvalue: float the max -log2(pvalue authorized usefull when managing inf vals)
      searchbox: bool whether or not to add a searchBox to interactively highlight genes
      logfoldtohighlight: float min logfoldchange when to diplay points
      pvaltohighlight: float min pvalue when to diplay points
      showlabels: bool whether or not to show a text above each datapoint with its label information

    Returns:
    --------
      The bokeh object
    """
    # pdb.set_trace()
    to_plot_not, to_plot_yes = selector(
        data, tohighlight if tohighlight is not None else [],
        logfoldtohighlight, pvaltohighlight)
    hover = bokeh.models.HoverTool(tooltips=tooltips, names=['circles'])

    # Create figure
    p = bokeh.plotting.figure(title=title, plot_width=650, plot_height=450)

    p.xgrid.grid_line_color = 'white'
    p.ygrid.grid_line_color = 'white'
    p.xaxis.axis_label = xlabel
    p.yaxis.axis_label = ylabel

    # Add the hover tool
    p.add_tools(hover)
    p, source1 = add_points(p,
                            to_plot_not,
                            'log2FoldChange',
                            'pvalue',
                            color='#1a9641',
                            maxvalue=maxvalue)
    p, source2 = add_points(p,
                            to_plot_yes,
                            'log2FoldChange',
                            'pvalue',
                            color='#fc8d59',
                            alpha=0.6,
                            outline=True,
                            maxvalue=maxvalue)
    if showlabels:
        labels = LabelSet(x='log2FoldChange',
                          y='transformed_q',
                          text_font_size='7pt',
                          text="gene_id",
                          level="glyph",
                          x_offset=5,
                          y_offset=5,
                          source=source2,
                          render_mode='canvas')
        p.add_layout(labels)
    if searchbox:
        text = TextInput(title="text", value="gene")
        text.js_on_change(
            'value',
            CustomJS(args=dict(source=source1),
                     code="""
      var data = source.data
      var value = cb_obj.value
      var gene_id = data.gene_id
      var a = -1
      for (i=0; i < gene_id.length; i++) {
          if ( gene_id[i]===value ) { a=i; console.log(i); data.size[i]=7; data.alpha[i]=1; data.color[i]='#fc8d59' }
      }
      source.data = data
      console.log(source)
      console.log(cb_obj)
      source.change.emit()
      console.log(source)
      """))
        p = column(text, p)
    p.output_backend = "svg"
    if folder:
        save(p, folder + title.replace(' ', "_") + "_volcano.html")
        export_svg(p,
                   filename=folder + title.replace(' ', "_") + "_volcano.svg")
    try:
        show(p)
    except:
        show(p)
    return p
Пример #7
0
    dict(average_grades=[7, 8, 10],
         exam_grades=[6, 9, 8],
         student_names=["Stephan", "Helder", "Riazudin"]))

source = ColumnDataSource(
    dict(average_grades=[7, 8, 10],
         exam_grades=[6, 9, 8],
         student_names=["Stephan", "Helder", "Riazudin"]))
#create figure
f = figure(x_range=Range1d(start=0, end=12), y_range=Range1d(start=0, end=12))

#add labels for glyphs --shows the labels in the top left, sigh
labels = LabelSet(x='average_grades',
                  y='exam_grades',
                  text='student_names',
                  x_offset=5,
                  y_offset=5,
                  source=source,
                  render_mode='css')  #adds an offset.
f.add_layout(labels)

#glyphs
f.circle(x='average_grades', y='exam_grades', source=source, size=8)


#create filtering slider
def filter_grades(attr, old, new):
    source.data = {
        key: [
            value for i, value in enumerate(source_original.data[key])
            if source_original.data['exam_grades'][i] >= slider.value
Пример #8
0
    "Hospitalized patients die of the disease or of natural causes",
    "Recovered individuals die of natural causes",
    "Recovered individuals lose their immunity and become susceptible again"
]

graph_renderer.selection_policy = NodesAndLinkedEdges()
graph_renderer.inspection_policy = EdgesAndLinkedNodes()

# add the labels to the nodes on the graph
xcoord = [1.15, .85, -.45, -1.2, -1.25, -1.25, -.15, .85]
ycoord = [0, .75, 1.05, .85, 0.1, -.95, -1.2, -.95]
label_source = ColumnDataSource(
    data=dict(x=xcoord, y=ycoord, names=class_names))
labels = LabelSet(x='x',
                  y='y',
                  text='names',
                  text_font_size="13px",
                  source=label_source,
                  render_mode='canvas')
plot.add_layout(labels)

plot.renderers.append(graph_renderer)

#solving the system of ODEs with original parameters to determine size of nodes
ret = solve_ivp(deriv,
                t_span=(0, 365),
                y0=y0,
                t_eval=t,
                args=(N, beta_A_uk, beta_A_k, beta_S_nh, beta_S_h, gamma,
                      gamma_hosp, nat_death, death_rate_S, death_rate_hosp,
                      E_to_I_forA, E_to_I_forS, return_rate, sd, test_rate_inc,
                      t_vac, health_capacity))
Пример #9
0
# elements['color'] = [element_color[standard_state] for standard_state in elements['standard_state']]

#convert elements dataframe into ColumnDataSource object, segment by solid, liquid, gas types
# solid = ColumnDataSource(elements['standard_state']=='solid'])
# gas = ColumnDataSource(elements['standard_state']=='gas'])
# liquid = ColumnDataSource(elements['standard_state']=='liquid'])

#create glyphs
# fig.circle(x='atomic radius',y='boiling point',size=[(s/10) for s in source.data['van_der_Waals_radius']],color='color',source=source)
# fig.circle(x='atomic radius',y='boiling point',size=[(s/10) for s in liquid.data['van_der_Waals_radius']],color='color',source=liquid)
# fig.circle(x='atomic radius',y='boiling point',size=[(s/10) for s in gas.data['van_der_Waals_radius']],color='color',source=gas)

#add labels for glyphs
label = LabelSet(x='atomic_radius',
                 y='boiling_point',
                 text='standard_state',
                 x_offset=5,
                 y_offset=5,
                 source=source)
# solid_label=LabelSet(x='atomic_radius',y='boiling_point',text='standard_state',x_offset=5,y_offset=5, source=solid)
# liquid_label=LabelSet(x='atomic_radius',y='boiling_point',text='standard_state',x_offset=5,y_offset=5, source=liquid)
# gas_label=LabelSet(x='atomic_radius',y='boiling_point',text='standard_state',x_offset=5,y_offset=5, source=gas)

fig.add_layout(label)
# fig.add_layout(solid_label)
# fig.add_layout(liquid_label)
# fig.add_layout(gas_label)

fig.circle(x='atomic_radius', y='boiling_point', color='color', source=source)


#create filtering function
Пример #10
0
                  'F', 'D-', 'D', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A',
                  'A+'
              ])

fig2 = figure(x_range=[
    'F', 'D-', 'D', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+'
],
              y_range=[
                  'F', 'D-', 'D', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A',
                  'A+'
              ])

#add labels for glyphs
labels1 = LabelSet(x='average_grades',
                   y='exam_grades',
                   text='student_names',
                   x_offset=5,
                   y_offset=5,
                   source=source1)
fig1.add_layout(labels1)

labels2 = LabelSet(x='average_grades',
                   y='exam_grades',
                   text='student_names',
                   x_offset=5,
                   y_offset=5,
                   source=source2)
fig2.add_layout(labels2)

#create glyphs
fig1.circle(x='average_grades', y='exam_grades', source=source1, size=8)
fig2.circle(x='average_grades', y='exam_grades', source=source2, size=8)
Пример #11
0
    Eyetracking_data.user.unique()),
                                      palette=Viridis256)

# set size of the dots in the future scatter plot
size_mapper = LinearInterpolator(x=[
    Eyetracking_data.FixationDuration.min(),
    Eyetracking_data.FixationDuration.max()
],
                                 y=[10, 50])

# scatter plot //  gaze plot

labels = LabelSet(x='x',
                  y='y',
                  text='index',
                  level='glyph',
                  x_offset=0,
                  y_offset=0,
                  source=source,
                  render_mode='canvas')

p4 = figure(title='Gaze plot',
            plot_width=p1.plot_width,
            plot_height=p1.plot_width,
            x_range=p1.x_range,
            y_range=p1.y_range,
            tools=TOOLS,
            tooltips=TOOLTIPS4,
            x_axis_label='x-axis',
            y_axis_label='y-axis')
p4.line(x='x', y='y', source=source, color='purple', line_width=2)
p4.circle(x='x',
Пример #12
0
    def top_graph(self, ind, title, d_source, e_source, tooltip, **kwargs):
        """Generate the top graphs (KH, uptake, WC)."""

        # Generate figure dict
        plot_side_size = 400
        fig_dict = dict(tools="pan,wheel_zoom,tap,reset,save",
                        active_scroll="wheel_zoom",
                        plot_width=plot_side_size,
                        plot_height=plot_side_size,
                        title=title)
        fig_dict.update(kwargs)

        # Create a colour mapper for number of isotherms
        mapper = log_cmap(field_name='{0}_n'.format(ind),
                          palette="Viridis256",
                          low_color='grey',
                          high_color='yellow',
                          low=3,
                          high=100)

        # Create a new plot
        graph = figure(**fig_dict)

        # Add the hover tooltip
        graph.add_tools(
            HoverTool(names=["{0}_data".format(ind)],
                      tooltips=tooltip.render(p=ind)))

        # Plot the data
        rend = graph.circle("{0}_x".format(ind),
                            "{0}_y".format(ind),
                            source=d_source,
                            size=10,
                            line_color=mapper,
                            color=mapper,
                            name="{0}_data".format(ind))

        # Plot guide line
        graph.add_layout(
            Slope(gradient=1,
                  y_intercept=0,
                  line_color='black',
                  line_dash='dashed',
                  line_width=2))

        # Plot the error margins
        graph.segment('{0}_x0'.format(ind),
                      '{0}_y0'.format(ind),
                      '{0}_x1'.format(ind),
                      '{0}_y1'.format(ind),
                      source=e_source,
                      color="black",
                      line_width=2,
                      line_cap='square',
                      line_dash='dotted')

        # Plot labels next to selected materials
        graph.add_layout(
            LabelSet(
                x='{0}_x'.format(ind),
                y='{0}_y'.format(ind),
                source=e_source,
                text='labels',
                level='glyph',
                x_offset=5,
                y_offset=5,
                render_mode='canvas',
                text_font_size='10pt',
            ))

        # Add the colorbar to the side
        graph.add_layout(
            ColorBar(color_mapper=mapper['transform'],
                     ticker=LogTicker(desired_num_ticks=10),
                     width=8,
                     location=(0, 0)), 'right')

        return graph, rend
output_notebook()

# data
fig_with_label_data = ColumnDataSource({'x': np.arange(10), 
                                        'y': [4, 7, 5, 5, 9, 2, 3, 4, 3, 4]})

# plot
fig_with_label = figure()
fig_with_label.line(x='x', y='y', source=fig_with_label_data)

# add label
label = Label(x=4, y=9, x_offset=10, text='Higest Point', text_baseline='middle')
fig_with_label.add_layout(label)

# add multiple labels
labels = LabelSet(x='x', y='y', text='y', level='glyph', source=fig_with_label_data)
fig_with_label.add_layout(labels)

# arrow annotation
fig_with_label.add_layout(Arrow(end=NormalHead(fill_color='orange'), x_start=5, y_start=7.5, x_end=4.5, y_end=8.8))

show(fig_with_label)
Loading BokehJS ...
Color Bar
In [79]:
cars.head()
Out[79]:
Acceleration	Cylinders	Displacement	Horsepower	Miles_per_Gallon	Name	Origin	Weight_in_lbs	Year
0	12.0	8	307.0	130.0	18.0	chevrolet chevelle malibu	USA	3504	1970-01-01
1	11.5	8	350.0	165.0	15.0	buick skylark 320	USA	3693	1970-01-01
2	11.0	8	318.0	150.0	18.0	plymouth satellite	USA	3436	1970-01-01
Пример #14
0
    plot.circle(
        x="swpay",
        y="earn",
        source=source_t,
        radius="clust_size",
        fill_color=linear_cmap("cluster", palette=Spectral7, low=0, high=6),
        # legend="cluster name",
        alpha=0.9,
    )

    labels_t = LabelSet(
        x="swpay",
        y="earn",
        source=source_t,
        text="cluster",
        level="glyph",
        text_align="center",
        y_offset=5,
        render_mode="canvas",
        text_font_size="8pt",
    )
    labels_c = LabelSet(
        x="swpay",
        y="earn",
        source=source_c,
        text="cluster",
        level="glyph",
        text_align="center",
        y_offset=5,
        render_mode="canvas",
        text_font_size="8pt",
Пример #15
0
def scatter(data,
            labels=None,
            title='scatter plot',
            showlabels=False,
            folder='',
            colors=None,
            xname='',
            yname="",
            importance=None,
            radi=5,
            alpha=0.8,
            colprovided=False,
            shape=None,
            **kwargs):
    """
    Makes an interactive scatter plot using Bokeh

    Args:
    -----
        data: array-like with shape [N,2]
        labels: list[str] a list of N names for each points or dict[str, list[str]] if you want multiple labels
        title: str the plot title
        showlabels: bool if the labels should be always displayed or not (else just on hover)
        colors: list[int] of N integers from 0 up to 256 for the dot's colors
        folder: str of location where to save the plot, won't save if empty
        xname: str the name of the x axes
        yname: str the name of the y axes
        importance: a list[int] of N values to scale the size of the dots and their opacity by
        radi: int the size of the dots
        alpha: float the opacity of the dots
        **kwargs: additional bokeh.figure args

    Returns:
    ------
        the bokeh object
    """
    TOOLS = "hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,save,box_select,lasso_select,"

    radii = []
    fill_alpha = []
    cols = []

    col = viridis(len(set(colors))) if colors is not None else ['#29788E'
                                                                ]  # (viridis1)
    for i in range(data.shape[0]):
        radii.append(radi if importance is None else radi /
                     (1 + importance[i]))
        fill_alpha.append(alpha if importance is None else alpha -
                          (0.2 * importance[i]))
        if not colprovided:
            cols.append(col[0] if colors is None else col[int(colors[i])])

    if shape is None:
        shape = [0] * data.shape[0]
    shape = np.array(shape)
    TOOLTIPS = [
        ("(x,y)", "(@x, @y)"),
    ]
    if type(labels) is list:
        TOOLTIPS.append(("label", "@labels"))
    elif type(labels) is dict:
        TOOLTIPS.extend([(str(i), "@" + str(i)) for i in list(labels.keys())])

    p = figure(tools=TOOLS, tooltips=TOOLTIPS, title=title)

    shaplot = {
        0: p.circle,
        1: p.star,
        2: p.square,
        3: p.triangle,
        4: p.cross,
        5: p.hex,
        6: p.diamond,
        7: p.inverted_triangle
    }

    shape_encoder = {val: i for i, val in enumerate(set(shape))}
    if len(set(shape)) > 8:
        raise ValueError("Too many shapes")
    for val in set(shape):
        di = dict(
            x=data[shape == val, 0],
            y=data[shape == val, 1],
            fill_color=np.array(cols)[shape == val]
            if not colprovided else np.array(colors)[shape == val],
            fill_alpha=np.array(fill_alpha)[shape == val],
            radius=np.array(radii)[shape == val],
        )

        if type(labels) is list:
            di.update({'labels': np.array(labels)[shape == val]})
        elif type(labels) is dict:
            di.update({
                va: np.array(label)[shape == val]
                for va, label in labels.items()
            })

        source = ColumnDataSource(data=di)

        shaplot[shape_encoder[val]]('x',
                                    'y',
                                    color='fill_color',
                                    fill_alpha='fill_alpha',
                                    line_width=0,
                                    source=source)
    p.xaxis[0].axis_label = xname
    p.yaxis[0].axis_label = yname
    if showlabels:
        labels = LabelSet(x='x',
                          y='y',
                          text='labels',
                          level='glyph',
                          text_font_size='9pt',
                          x_offset=5,
                          y_offset=5,
                          source=source,
                          render_mode='canvas')
        p.add_layout(labels)
    p.output_backend = "svg"
    try:
        show(p)
    except:
        show(p)
    if folder:
        save(p, folder + title.replace(' ', "_") + "_scatter.html")
        export_svg(p,
                   filename=folder + title.replace(' ', "_") + "_scatter.svg")
    return p
Пример #16
0
def visual_treat(vehicles, op_data):
    """
    This method is used for generating a bokeh plot
    :param vehicles: gets the number of vehicles
    :param op_data: pandas dataframe that contains the solution
    :return:
    """

    TOOLS = "hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom," \
            "undo,redo,reset,tap,save,box_select,poly_select,lasso_select,"
    mypalette = Spectral11[0:vehicles]

    f = figure(tools=TOOLS)

    # styling the plot area

    f.plot_height = 650
    f.plot_width = 1100
    f.background_fill_color = "olive"
    f.background_fill_alpha = 0.2

    #styling the title
    f.title.text = "Vehicle Routing Problem"
    f.title.text_color = "olive"
    f.title.text_font = "verdana"
    f.title.text_font_size = "22px"
    f.title.align = "center"

    #styling the axes
    f.xaxis.axis_label = "X-Axis"
    f.yaxis.axis_label = "Y-Axis"
    f.yaxis.major_label_orientation = "vertical"
    f.axis.axis_label_text_color = "blue"

    #styling the grid
    f.toolbar.logo = None

    sites = ColumnDataSource(
        dict(x_sites=op_data['x-cor'][1:],
             y_sites=op_data['y-cor'][1:],
             ix_sites=list(op_data.index.values[1:])))

    #adding labels
    labels = LabelSet(x="x_sites",
                      y="y_sites",
                      text="ix_sites",
                      level='glyph',
                      x_offset=5,
                      y_offset=5,
                      source=sites,
                      render_mode='canvas')

    cds = ColumnDataSource(op_data)
    x_depot = cds.data['x-cor'][0]
    y_depot = cds.data['y-cor'][0]
    f.circle(x=x_depot, y=y_depot, source=cds, size=15, color='red')
    f.circle(x="x_sites", y="y_sites", source=sites, size=7, color='blue')

    f.add_layout(labels)

    route_counter = 0
    for column in op_data:
        if column.startswith('Route'):
            x_line = []
            y_line = []
            x_line.append(cds.data['x-cor'][0])
            y_line.append(cds.data['y-cor'][0])

            for i in range(int(max(cds.data[column])), -1, -1):
                ind = op_data[op_data[column] == i].index[0]
                x_line.append(cds.data['x-cor'][ind])
                y_line.append(cds.data['y-cor'][ind])
            f.line(x=x_line,
                   y=y_line,
                   line_color=mypalette[route_counter],
                   line_width=3,
                   legend=str(column))
            route_counter += 1

    #styling the legend
    f.legend.location = "top_left"

    #output file
    output_file("vehicle_routing.html")

    show(f)

    return None
Пример #17
0
              exam_grades=['A+', 'C', 'D'],
              students=['Stephan', 'Helder', 'Riazudidn']))

# create the figure
f = figure(x_range=[
    'F', 'D-', 'D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+'
],
           y_range=[
               'F', 'D-', 'D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-',
               'A', 'A+'
           ])

# add labels for glyphs
labels = LabelSet(x='average_grades',
                  y='exam_grades',
                  text='students',
                  x_offset=5,
                  y_offset=5,
                  source=source)

f.add_layout(labels)

# add labels for glyphs
f.circle(x='average_grades', y='exam_grades', size=8, source=source)


# create function
def update_labels(attr, old, new):
    labels.text = select.value


# add select widgets
    counter = Counter(frequency_dict)
    top_1000 = [x[0] for x in counter.most_common(1000)]

    # Visualise in 2D.
    tsne_obj = TSNE(n_components=2, random_state=0)
    words_top_1000_vectors = model[top_1000]
    words_top_1000_tsne = tsne_obj.fit_transform(words_top_1000_vectors)

    fig = figure(
        tools="pan,wheel_zoom,reset,save",
        toolbar_location="above",
        title="word2vec T-SNE visualisation for top 1000 words - wikipedia")

    source = ColumnDataSource(data=dict(x1=words_top_1000_tsne[:, 0],
                                        x2=words_top_1000_tsne[:, 1],
                                        names=top_1000))

    fig.scatter(x="x1", y="x2", size=9, source=source)

    labels = LabelSet(x="x1",
                      y="x2",
                      text="names",
                      y_offset=6,
                      text_font_size="9pt",
                      text_color="#555555",
                      source=source,
                      text_align='center')

    fig.add_layout(labels)
    show(fig)
Пример #19
0
         exam_grades=["A+", "C", "D"],
         student_names=["Stephan", "Helder", "Riazudidn"]))

#create the figure
f = figure(x_range=[
    "F", "D-", "D", "D+", "C-", "C", "C+", "B-", "B", "B+", "A-", "A", "A+"
],
           y_range=[
               "F", "D-", "D", "D+", "C-", "C", "C+", "B-", "B", "B+", "A-",
               "A", "A+"
           ])

#add labels for glyphs
labels = LabelSet(x="average_grades",
                  y="exam_grades",
                  text="student_names",
                  x_offset=5,
                  y_offset=5,
                  source=source)
f.add_layout(labels)

#create glyphs
f.circle(x="average_grades", y="exam_grades", source=source, size=8)


#create function
def update_labels(attr, old, new):
    labels.text = options[radio_button_group.active]


''' ran change from original '''
Пример #20
0
#f.x_range=Range1d(start=0,end=10) # to define axes
#f.y_range=Range1d(start=0,end=5)
#f.xaxis.bounds=(2,8) # to restrict axis showed
f.xaxis[0].ticker.desired_num_ticks=6

#Styling legend
f.legend.location='top_left'
f.legend.background_fill_alpha=0
f.legend.border_line_color=None
f.legend.margin=60


#create a span annotation for f
span_4=Span(location=4,dimension='height',line_color='red',line_width=2)
f.add_layout(span_4)

#create a box annotation
box_2_6=BoxAnnotation(left=2,right=6,fill_color='firebrick',fill_alpha=0.2)
f.add_layout(box_2_6)

#create annotation
description=Label(x=6,y=0.25,text='This graph is for testing', render_mode='css', text_font_size='10px')
f.add_layout(description)

#create labeles for glyphs
labels=LabelSet(x='petal_length',y='petal_width',text='species', source=setosa, text_font_size='5px')
f.add_layout(labels)

#grid= gridplot([[f],[f1]])

show(f)