bokeh.models.MultiLine

Here are the examples of the python api bokeh.models.MultiLine taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

12 Examples 7

3 Source : calendar.py
with GNU Affero General Public License v3.0
from andrewcooke

    def _sqarc(self, df, line_alpha=CALENDAR_ALPHA, color=CALENDAR_COLOR):
        df = df.dropna().copy()  # copy to avoid set on view errors
        xys = list(_corners(df))
        xs, ys = list(zip(*xys))
        df.loc[:, CALENDAR_XS] = xs
        df.loc[:, CALENDAR_YS] = ys
        multi = MultiLine(xs=CALENDAR_XS, ys=CALENDAR_YS, line_color=color, line_alpha=line_alpha)
        self._plot.add_glyph(ColumnDataSource(df), multi)


# helpers for generating square arc multiline (a lot of work for not much result)

def _edge(linear, x, y, r):

3 Source : test_renderers.py
with MIT License
from rthorst

def test_graphrenderer_check_malformed_graph_source_no_edge_start_or_end():
    edge_source = ColumnDataSource()
    edge_renderer = GlyphRenderer(data_source=edge_source, glyph=MultiLine())
    renderer = GraphRenderer(edge_renderer=edge_renderer)

    check = renderer._check_malformed_graph_source()
    assert check != []

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

#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------

0 Source : draw.py
with Apache License 2.0
from aws

def circuit_from(bqm):
    G = bqm.to_networkx_graph()
    plot = Plot(
        plot_width=600, plot_height=400, x_range=Range1d(-0.1, 1.1), y_range=Range1d(-0.1, 1.1)
    )
    plot.title.text = "Multiplication as a BQM"
    plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())
    graph_renderer = from_networkx(G, circuit_layout)

    circle_size = 25
    graph_renderer.node_renderer.glyph = Circle(size=circle_size, fill_color="#F5F7FB")
    graph_renderer.node_renderer.selection_glyph = Circle(size=circle_size, fill_color="#EEA64E")
    graph_renderer.node_renderer.hover_glyph = Circle(size=circle_size, fill_color="#FFE86C")

    edge_size = 2
    graph_renderer.edge_renderer.glyph = MultiLine(
        line_color="#CCCCCC", line_alpha=0.8, line_width=edge_size
    )
    graph_renderer.edge_renderer.selection_glyph = MultiLine(
        line_color="#EEA64E", line_width=edge_size
    )
    graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color="#FFE86C", line_width=edge_size)

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

    plot.renderers.append(graph_renderer)

    plot.background_fill_color = "#202239"

    add_labels(plot)
    show(Row(plot))


def frequency_of(results):

0 Source : draw.py
with Apache License 2.0
from aws

def draw(S, position=None, with_labels=False):
    """Plot the given signed social network.

    Args:
        S: The network
        position (dict, optional):
            The position for the nodes. If no position is provided, a layout will be calculated. If the nodes have
            'color' attributes, a Kamanda-Kawai layout will be used to group nodes of the same color together.
            Otherwise, a circular layout will be used.

    Returns:
        A dictionary of positions keyed by node.

    Examples:
    >>> import dwave_structural_imbalance_demo as sbdemo
    >>> gssn = sbdemo.GlobalSignedSocialNetwork()
    >>> nld_before = gssn.get_node_link_data('Syria', 2013)
    >>> nld_after = gssn.solve_structural_imbalance('Syria', 2013)
    # draw Global graph before solving; save node layout for reuse
    >>> position = sbdemo.draw('syria.png', nld_before)
    # draw the Global graph; reusing the above layout, and calculating a new grouped layout
    >>> sbdemo.draw('syria_imbalance.png', nld_after, position)
    >>> sbdemo.draw('syria_imbalance_grouped', nld_after)

    """

    # we need a consistent ordering of the edges
    edgelist = S.edges()
    nodelist = S.nodes()

    def layout_wrapper(S):
        pos = position
        if pos is None:
            try:
                # group bipartition if nodes are colored
                dist = defaultdict(dict)
                for u, v in product(nodelist, repeat=2):
                    if u == v:  # node has no distance from itself
                        dist[u][v] = 0
                    elif (
                        nodelist[u]["color"] == nodelist[v]["color"]
                    ):  # make same color nodes closer together
                        dist[u][v] = 1
                    else:  # make different color nodes further apart
                        dist[u][v] = 2
                pos = nx.kamada_kawai_layout(S, dist)
            except KeyError:
                # default to circular layout if nodes aren't colored
                pos = nx.circular_layout(S)
        return pos

    # call layout wrapper once with all nodes to store position for calls with partial graph
    position = layout_wrapper(S)

    plot = Plot(
        plot_width=600, plot_height=400, x_range=Range1d(-1.2, 1.2), y_range=Range1d(-1.2, 1.2)
    )
    tools = [WheelZoomTool(), ZoomInTool(), ZoomOutTool(), PanTool()]
    plot.add_tools(*tools)
    plot.toolbar.active_scroll = tools[0]

    def get_graph_renderer(S, line_dash):
        # we need a consistent ordering of the edges
        edgelist = S.edges()
        nodelist = S.nodes()

        # get the colors assigned to each edge based on friendly/hostile
        sign_edge_color = ["#87DACD" if S[u][v]["sign"] == 1 else "#FC9291" for u, v in edgelist]

        # get the colors assigned to each node by coloring
        try:
            coloring_node_color = [
                "#4378F8" if nodelist[v]["color"] else "#FFE897" for v in nodelist
            ]
        except KeyError:
            coloring_node_color = ["#FFFFFF" for __ in nodelist]

        graph_renderer = from_networkx(S, layout_wrapper)

        circle_size = 10
        graph_renderer.node_renderer.data_source.add(coloring_node_color, "color")
        graph_renderer.node_renderer.glyph = Circle(size=circle_size, fill_color="color")

        edge_size = 2
        graph_renderer.edge_renderer.data_source.add(sign_edge_color, "color")
        try:
            graph_renderer.edge_renderer.data_source.add(
                [S[u][v]["event_year"] for u, v in edgelist], "event_year"
            )
            graph_renderer.edge_renderer.data_source.add(
                [S[u][v]["event_description"] for u, v in edgelist], "event_description"
            )
            plot.add_tools(
                HoverTool(
                    tooltips=[("Year", "@event_year"), ("Description", "@event_description")],
                    line_policy="interp",
                )
            )
        except KeyError:
            pass
        graph_renderer.edge_renderer.glyph = MultiLine(line_color="color", line_dash=line_dash)

        graph_renderer.inspection_policy = EdgesAndLinkedNodes()

        return graph_renderer

    try:
        S_dash = S.edge_subgraph(((u, v) for u, v in edgelist if S[u][v]["frustrated"]))
        S_solid = S.edge_subgraph(((u, v) for u, v in edgelist if not S[u][v]["frustrated"]))
        plot.renderers.append(get_graph_renderer(S_dash, "dashed"))
        plot.renderers.append(get_graph_renderer(S_solid, "solid"))
    except KeyError:
        plot.renderers.append(get_graph_renderer(S, "solid"))

    plot.background_fill_color = "#202239"

    positions = layout_wrapper(S)
    if with_labels:
        data = {"xpos": [], "ypos": [], "label": []}
        for label, pos in positions.items():
            data["label"].append(label)
            data["xpos"].append(pos[0])
            data["ypos"].append(pos[1])

        labels = LabelSet(
            x="xpos",
            y="ypos",
            text="label",
            level="glyph",
            source=ColumnDataSource(data),
            x_offset=-5,
            y_offset=10,
            text_color="#F5F7FB",
            text_font_size="12pt",
        )
        plot.add_layout(labels)

    show(Row(plot))

    return positions

0 Source : plotting.py
with BSD 3-Clause "New" or "Revised" License
from BuildACell

def graphPlot(DG,DGspecies,DGreactions,plot,layout="force",positions=None,plot_species = True, plot_reactions = True, plot_edges = True, plot_arrows = True,\
              species_glyph_size = 12, reaction_glyph_size = 8, posscale = 1.0,layoutfunc=None,iterations=2000,rseed=30,show_species_images=False):
    """given a directed graph, plot it!
    Inputs:
    DG: a directed graph of type DiGraph
    DGspecies: a directed graph which only contains the species nodes
    DGreactions: a directed graph which only contains the reaction nodes
    plot: a bokeh plot object
    layout: graph layout function. 
                'force' uses fa2 to push nodes apart
                'circle' plots the nodes and reactions in two overlapping circles, with the reactions on the inside of the circle
                'custom' allows user input "layoutfunc". Internally, layoutfunc is passed the three inputs (DG, DGspecies, DGreactions)
                                                        and should output a position dictionary with node {  <  node number>:(x,y)}

    positions: a dictionary of node names and x,y positions. this gets passed into the layout function
    posscale: multiply the scaling of the plot. This only affects the arrows because the arrows are a hack :("""
    random.seed(rseed)
    if(not PLOT_NETWORK):
        warn("network plotting disabled because some libraries are not found")
        return
    if(layout == "force"):
        # below are parameters for the force directed graph visualization
        forceatlas2 = ForceAtlas2(
            # Behavior alternatives
            outboundAttractionDistribution=True,  # Dissuade hubs
            linLogMode=False,  # NOT IMPLEMENTED
            # Prevent overlap (NOT IMPLEMENTED)
            adjustSizes=False,
            edgeWeightInfluence=1.0,

            # Performance
            jitterTolerance=1.0,  # Tolerance
            barnesHutOptimize=True,
            barnesHutTheta=1.2,
            multiThreaded=False,  # NOT IMPLEMENTED

            # Tuning
            scalingRatio=2.4*posscale,
            strongGravityMode=False,
            gravity=1.0,

            # Log
            verbose=False)

        positions = forceatlas2.forceatlas2_networkx_layout(
            DG, pos=positions, iterations=iterations)
    elif(layout == "circle"):
        positions = nx.circular_layout(DGspecies, scale=50*posscale)
        positions.update(nx.circular_layout(DGreactions, scale=35*posscale))
    elif(layout == "custom"):
        positions = layoutfunc(DG, DGspecies, DGreactions)
    reaction_renderer = from_networkx(DGreactions, positions, center=(0, 0))
    species_renderer = from_networkx(DGspecies, positions, center=(0, 0))
    edges_renderer = from_networkx(DG, positions, center=(0, 0))

    #Set xbounds and ybounds:
    xbounds = [0, 0]
    ybounds = [0, 0]
    for n in positions:
        xbounds[0] = min([xbounds[0], positions[n][0]])
        xbounds[1] = max([xbounds[1], positions[n][0]])
        ybounds[0] = min([ybounds[0], positions[n][1]])
        ybounds[1] = max([ybounds[1], positions[n][1]])

    max_glyph = max([reaction_glyph_size, species_glyph_size])
    xbounds[0] -= max_glyph
    xbounds[1] += max_glyph
    ybounds[0] -= max_glyph
    ybounds[1] += max_glyph

    # edges
    edges_renderer.node_renderer.glyph = Circle(
        size=species_glyph_size, line_alpha=0, fill_alpha=0, fill_color="color")
    edges_renderer.edge_renderer.glyph = MultiLine(
        line_alpha=0.2, line_width=4, line_join="round", line_color="color")
    edges_renderer.edge_renderer.selection_glyph = MultiLine(
        line_color=Spectral4[2], line_width=5, line_join="round")
    edges_renderer.edge_renderer.hover_glyph = MultiLine(
        line_color=Spectral4[1], line_width=5, line_join="round")
    if plot_arrows:
        xbounds_a, ybounds_a = makeArrows2(
            edges_renderer, DG, positions, headsize=5)  # make the arrows!
        xbounds[0] = min([xbounds[0], xbounds_a[0]])
        xbounds[1] = max([xbounds[1], xbounds_a[1]])
        ybounds[0] = min([ybounds[0], ybounds_a[0]])
        ybounds[1] = max([ybounds[1], ybounds_a[1]])

    # we want to find the middle of the graph and plot a square that is 1:1 aspect ratio

    # find the midpoint of the graph
    xmid = statistics.mean(xbounds)
    ymid = statistics.mean(ybounds)
    # now, subtract the middle from the edges
    xmiddlized = [a-xmid for a in xbounds]
    ymiddlized = [a-ymid for a in ybounds]
    # now, find the biggest dimension
    absdim = max([abs(a) for a in xmiddlized+ymiddlized])
    xlim = [xmid-absdim*1.05, xmid + absdim*1.05]
    ylim = [ymid-absdim*1.05, ymid + absdim*1.05]
    # now set it on the plot!
    plot.x_range = Range1d(xlim[0], xlim[1])
    plot.y_range = Range1d(ylim[0], ylim[1])

    # reactions
    reaction_renderer.node_renderer.glyph = Square(
        size=reaction_glyph_size, fill_color="color")
    reaction_renderer.node_renderer.selection_glyph = Square(
        size=reaction_glyph_size, fill_color=Spectral4[2])
    reaction_renderer.node_renderer.hover_glyph = Square(
        size=reaction_glyph_size, fill_color=Spectral4[1])

    # nodes
    species_renderer.node_renderer.glyph = Circle(size=12, fill_color="color")
    species_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
    species_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])
    
    #this part adds the interactive elements that make it so that the lines are highlighted 
    #when you mouse over and click
    edge_hover_tool = HoverTool(tooltips= None,renderers=[edges_renderer])
    if( not show_species_images):
        species_hover_tool = HoverTool(tooltips=[("name", "@species"), ("type", "@type")],\
                                        renderers=[species_renderer],attachment="right")
    else:
        species_hover_tool = HoverTool(tooltips=' < div> < div>  < img src="data:image/png;base64,@image" style="float: left; margin: 0px 0px 0px 0px;"> < /img> < /div> < /div>',\
                                        renderers=[species_renderer],attachment="right")
    rxn_hover_tool = HoverTool(tooltips=[("reaction", "@species"), ("type", "@type"),("k_f","@k"),("k_r","@k_r")],\
                                        renderers=[reaction_renderer],attachment="right")
    
    plot.add_tools(edge_hover_tool,species_hover_tool,rxn_hover_tool, TapTool(), BoxSelectTool(),PanTool(),WheelZoomTool())

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

    if plot_edges:
        plot.renderers.append(edges_renderer)
    if plot_reactions:
        plot.renderers.append(reaction_renderer)
    if plot_species:
        plot.renderers.append(species_renderer)

def generate_networkx_graph(CRN,useweights=False,use_pretty_print=False,pp_show_material=True,

0 Source : plotting.py
with BSD 3-Clause "New" or "Revised" License
from FeatureLabs

def dendrogram(D, figargs=None):
    '''Creates a dendrogram plot.
    This plot can show full structure of a given dendrogram.

    Args:
        D (henchman.selection.Dendrogram): An initialized dendrogram object

    Examples:
        >>> from henchman.selection import Dendrogram
        >>> from henchman.plotting import show
        >>> import henchman.plotting as hplot
        >>> D = Dendrogram(X)
        >>> plot = hplot.dendrogram(D)
        >>> show(plot)
    '''
    if figargs is None:
        return lambda figargs: dendrogram(D, figargs=figargs)
    G = nx.Graph()

    vertices_source = ColumnDataSource(
        pd.DataFrame({'index': D.columns.keys(),
                      'desc': list(D.columns.values())}))
    edges_source = ColumnDataSource(
        pd.DataFrame(D.edges[0]).rename(
            columns={1: 'end', 0: 'start'}))
    step_source = ColumnDataSource(
        pd.DataFrame({'step': [0],
                      'thresh': [D.threshlist[0]],
                      'components': [len(D.graphs[0])]}))

    G.add_nodes_from([str(x) for x in vertices_source.data['index']])
    G.add_edges_from(zip(
        [str(x) for x in edges_source.data['start']],
        [str(x) for x in edges_source.data['end']]))

    graph_renderer = from_networkx(G, nx.circular_layout,
                                   scale=1, center=(0, 0))

    graph_renderer.node_renderer.data_source = vertices_source
    graph_renderer.node_renderer.view = CDSView(source=vertices_source)
    graph_renderer.edge_renderer.data_source = edges_source
    graph_renderer.edge_renderer.view = CDSView(source=edges_source)

    plot = Plot(plot_width=400, plot_height=400,
                x_range=Range1d(-1.1, 1.1),
                y_range=Range1d(-1.1, 1.1))
    plot.title.text = "Feature Connectivity"
    graph_renderer.node_renderer.glyph = Circle(
        size=5, fill_color=Spectral4[0])
    graph_renderer.node_renderer.selection_glyph = Circle(
        size=15, fill_color=Spectral4[2])
    graph_renderer.edge_renderer.data_source = edges_source
    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
                                                   line_alpha=0.6,
                                                   line_width=.5)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(
        line_color=Spectral4[2],
        line_width=3)
    graph_renderer.node_renderer.hover_glyph = Circle(
        size=5,
        fill_color=Spectral4[1])
    graph_renderer.selection_policy = NodesAndLinkedEdges()
    graph_renderer.inspection_policy = NodesAndLinkedEdges()

    plot.renderers.append(graph_renderer)

    plot.add_tools(
        HoverTool(tooltips=[("feature", "@desc"),
                            ("index", "@index"), ]),
        TapTool(),
        BoxZoomTool(),
        SaveTool(),
        ResetTool())

    plot = _modify_plot(plot, figargs)

    if figargs['static']:
        return plot

    def modify_doc(doc, D, figargs):
        data_table = DataTable(source=step_source,
                               columns=[TableColumn(field='step',
                                                    title='Step'),
                                        TableColumn(field='thresh',
                                                    title='Thresh'),
                                        TableColumn(field='components',
                                                    title='Components')],
                               height=50, width=400)

        def callback(attr, old, new):
            try:
                edges = D.edges[slider.value]
                edges_source.data = ColumnDataSource(
                    pd.DataFrame(edges).rename(columns={1: 'end',
                                                        0: 'start'})).data
                step_source.data = ColumnDataSource(
                    {'step': [slider.value],
                     'thresh': [D.threshlist[slider.value]],
                     'components': [len(D.graphs[slider.value])]}).data
            except Exception as e:
                print(e)

        slider = Slider(start=0,
                        end=(len(D.edges) - 1),
                        value=0,
                        step=1,
                        title="Step")
        slider.on_change('value', callback)

        doc.add_root(column(slider, data_table, plot))
    return lambda doc: modify_doc(doc, D, figargs)


def f1(X, y, model, n_precs=1000, n_splits=1, figargs=None):

0 Source : clustree.py
with MIT License
from ivirshup

def gen_clustree_plot(
    g: nx.Graph,
    pos: dict = None,
    plot_kwargs: dict = None,
    node_kwargs: dict = None,
    edge_kwargs: dict = None,
):
    """
    Takes a graph, basically just instantiates a plot

    Args:
        g: clustree graph.
        pos: dict containing calculated layout positions
    """
    if pos is None:
        pos = nx.nx_agraph.graphviz_layout(g, prog="dot")
    if plot_kwargs is None:
        plot_kwargs = dict(plot_width=1000, plot_height=600)
    if node_kwargs is None:
        node_kwargs = dict(size=15)
    if edge_kwargs is None:
        edge_kwargs = dict(line_alpha="edge_alpha", line_width=1)

    g_p = g.copy()
    # set_edge_alpha(g_p)

    plot = Plot(**get_ranges(pos), **plot_kwargs)

    graph_renderer = from_networkx(g_p, pos)
    graph_renderer.node_renderer.glyph = Circle(**node_kwargs)
    graph_renderer.edge_renderer.glyph = MultiLine(**edge_kwargs)

    plot.renderers.append(graph_renderer)

    # node_hover = HoverTool(
    #     tooltips=[("solution_name", "@solution_name"),
    #               ("partition_id", "@partition_id"), ("n_items", "@n_items")]
    # )

    # plot.add_tools(node_hover)

    return plot


def get_ranges(pos):

0 Source : clustree.py
with MIT License
from ivirshup

def plot_hierarchy(
    complist: "ComponentList", coords: pd.DataFrame, *, scatter_kwargs={}
):
    """
    Params
    ------
    complist
        List of components that will be plotted in this graph.
    """
    coords = coords.copy()
    scatter_kwargs = scatter_kwargs.copy()
    g = complist.to_graph()
    assert len(list(nx.components.weakly_connected_components(g))) == 1
    for k, v in make_umap_plots(
        complist, coords, scatter_kwargs=scatter_kwargs
    ).items():
        g.nodes[k]["img"] = v

    pos = json_friendly(
        nx.nx_agraph.graphviz_layout(nx.DiGraph(g.edges(data=False)), prog="dot")
    )

    graph_renderer = from_networkx(g, pos)
    graph_renderer.node_renderer.glyph = Circle(size=15)
    graph_renderer.edge_renderer.glyph = MultiLine(line_width=1)

    node_hover = HoverTool(
        tooltips=[
            ("img", "@img{safe}"),
            ("component_id", "@index"),
            ("# solutions:", "@n_solutions"),
            ("# samples in intersect", "@n_intersect"),
            ("# samples in union", "@n_union"),
        ],
        attachment="vertical",
    )

    # Adding labels
    label_src = pd.DataFrame.from_dict(
        graph_renderer.layout_provider.graph_layout, orient="index", columns=["x", "y"]
    )
    label_src.index.name = "nodeid"
    label_src = ColumnDataSource(label_src)

    node_label = LabelSet(
        x="x",
        y="y",
        text="nodeid",
        level="annotation",
        source=label_src,
        text_align="center",
    )

    # layout = graph_renderer.layout_provider.graph_layout
    # label, x, y = zip(*((str(label), x, y) for label, (x, y) in layout.items()))
    # node_label = LabelSet(
    #     x=x, y=y, text=label, level="glyph"
    # )

    p = Plot(plot_width=1000, plot_height=500, **get_ranges(pos))
    p.renderers.append(graph_renderer)
    p.add_layout(node_label)
    p.add_tools(node_hover, SaveTool())
    return p

0 Source : visualize_utils.py
with MIT License
from ratsgo

def visualize_self_attention_scores(tokens, scores, filename="/notebooks/embedding/self-attention.png",
                                    use_notebook=False):
    mean_prob = np.mean(scores)
    weighted_edges = []
    for idx_1, token_prob_dist_1 in enumerate(scores):
        for idx_2, el in enumerate(token_prob_dist_1):
            if idx_1 == idx_2 or el   <   mean_prob:
                weighted_edges.append((tokens[idx_1], tokens[idx_2], 0))
            else:
                weighted_edges.append((tokens[idx_1], tokens[idx_2], el))
    max_prob = np.max([el[2] for el in weighted_edges])
    weighted_edges = [(el[0], el[1], (el[2] - mean_prob) / (max_prob - mean_prob)) for el in weighted_edges]

    G = nx.Graph()
    G.add_nodes_from([el for el in tokens])
    G.add_weighted_edges_from(weighted_edges)

    plot = Plot(plot_width=500, plot_height=500,
                x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1))
    plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())

    graph_renderer = from_networkx(G, nx.circular_layout, scale=1, center=(0, 0))

    graph_renderer.node_renderer.data_source.data['colors'] = Spectral8[:len(tokens)]
    graph_renderer.node_renderer.glyph = Circle(size=15, line_color=None, fill_color="colors")
    graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color="colors")
    graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color="grey")

    graph_renderer.edge_renderer.data_source.data["line_width"] = [G.get_edge_data(a, b)['weight'] * 3 for a, b in
                                                                   G.edges()]
    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_width={'field': 'line_width'})
    graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color="grey", line_width=5)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color="grey", line_width=5)

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

    plot.renderers.append(graph_renderer)

    x, y = zip(*graph_renderer.layout_provider.graph_layout.values())
    data = {'x': list(x), 'y': list(y), 'connectionNames': tokens}
    source = ColumnDataSource(data)
    labels = LabelSet(x='x', y='y', text='connectionNames', source=source, text_align='center')
    plot.renderers.append(labels)
    plot.add_tools(SaveTool())
    if use_notebook:
        output_notebook()
        show(plot)
    else:
        export_png(plot, filename)
        print("save @ " + filename)


def visualize_words(words, vecs, palette="Viridis256", filename="/notebooks/embedding/words.png",

0 Source : showMatLabFig._spatioTemporal.py
with MIT License
from richieBao

def interactiveG(G):
    from bokeh.models.graphs import NodesAndLinkedEdges,from_networkx
    from bokeh.models import Circle, HoverTool, MultiLine,Plot,Range1d,StaticLayoutProvider
    from bokeh.plotting import figure, output_file, show, ColumnDataSource
    from bokeh.io import output_notebook, show
    output_notebook()
    # We could use figure here but don't want all the axes and titles  
    #plot=Plot(plot_width=1600, plot_height=300, tooltips=TOOLTIPS,title="PHmi+landmarks+route+power(10,-5)",x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))
    
    output_file("PHMI_network")
    source=ColumnDataSource(data=dict(
        x=locations[0].tolist(),
        #x=[idx for idx in range(len(PHMIList))],
        #y=locations[1].tolist(),
        y=PHMIList,
        #desc=[str(i) for i in PHMIList],
        #PHMI_value=PHMI_dic[0][0].tolist(),    
    ))
    TOOLTIPS=[
        ("index", "$index"),
        ("(x,y)", "($x, $y)"),
        #("desc", "@desc"),
        #("PHMI", "$PHMI_value"),
    ]
    
    
    plot=figure(x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1),plot_width=2200, plot_height=500,tooltips=TOOLTIPS,title="PHMI_network")
    
    #G_position={key:(G.position[key][1],G.position[key][0]) for key in G.position.keys()}
    graph = from_networkx(G,nx.spring_layout,scale=1, center=(0,0))  
    #plot.renderers.append(graph) 
    
    fixed_layout_provider = StaticLayoutProvider(graph_layout=G.position)
    graph.layout_provider = fixed_layout_provider
    plot.renderers.append(graph)
    
    # Blue circles for nodes, and light grey lines for edges  
    graph.node_renderer.glyph = Circle(size=5, fill_color='#2b83ba')  
    graph.edge_renderer.glyph = MultiLine(line_color="#cccccc", line_alpha=0.8, line_width=2)  
      
    # green hover for both nodes and edges  
    graph.node_renderer.hover_glyph = Circle(size=25, fill_color='#abdda4')  
    graph.edge_renderer.hover_glyph = MultiLine(line_color='#abdda4', line_width=4)  
      
    # When we hover over nodes, highlight adjecent edges too  
    graph.inspection_policy = NodesAndLinkedEdges()  
      
    plot.add_tools(HoverTool(tooltips=None))  
     
    colors=('aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen')
    ScalePhmi=math.pow(10,1)
    i=0
    for val,idx in zip(phmi_breakPtsNeg, plot_x):
        plot.line(idx,np.array(val)*ScalePhmi,line_color=colors[i])
        i+=1    
        
    show(plot)
    
#06-single landmarks pattern 无人车位置点与对应landmarks栅格图
#convert location and corresponding landmarks to raster data format using numpy.histogram2d
def colorMesh_phmi(landmarks,locations,targetPts_idx,Phmi):

0 Source : driverlessCityProject_spatialPointsPattern_association_basic.py
with MIT License
from richieBao

def interactiveG(G):
    from bokeh.models.graphs import NodesAndLinkedEdges,from_networkx
    from bokeh.models import Circle, HoverTool, MultiLine,Plot,Range1d,StaticLayoutProvider
    from bokeh.plotting import figure, output_file, show, ColumnDataSource
    from bokeh.io import output_notebook, show
    output_notebook()
    # We could use figure here but don't want all the axes and titles  
    #plot=Plot(plot_width=1600, plot_height=300, tooltips=TOOLTIPS,title="PHmi+landmarks+route+power(10,-5)",x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))
    
    output_file("PHMI_network")
    source=ColumnDataSource(data=dict(
        x=locations[0].tolist(),
        #x=[idx for idx in range(len(PHMIList))],
        #y=locations[1].tolist(),
        y=PHMIList,
        #desc=[str(i) for i in PHMIList],
        #PHMI_value=PHMI_dic[0][0].tolist(),    
    ))
    TOOLTIPS=[
        ("index", "$index"),
        ("(x,y)", "($x, $y)"),
        #("desc", "@desc"),
        #("PHMI", "$PHMI_value"),
    ]
    
    
    plot=figure(x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1),plot_width=2200, plot_height=500,tooltips=TOOLTIPS,title="PHMI_network")
    
    #G_position={key:(G.position[key][1],G.position[key][0]) for key in G.position.keys()}
    graph = from_networkx(G,nx.spring_layout,scale=1, center=(0,0))  
    #plot.renderers.append(graph) 
    
    fixed_layout_provider = StaticLayoutProvider(graph_layout=G.position)
    graph.layout_provider = fixed_layout_provider
    plot.renderers.append(graph)
    
    # Blue circles for nodes, and light grey lines for edges  
    graph.node_renderer.glyph = Circle(size=5, fill_color='#2b83ba')  
    graph.edge_renderer.glyph = MultiLine(line_color="#cccccc", line_alpha=0.8, line_width=2)  
      
    # green hover for both nodes and edges  
    graph.node_renderer.hover_glyph = Circle(size=25, fill_color='#abdda4')  
    graph.edge_renderer.hover_glyph = MultiLine(line_color='#abdda4', line_width=4)  
      
    # When we hover over nodes, highlight adjecent edges too  
    graph.inspection_policy = NodesAndLinkedEdges()  
      
    plot.add_tools(HoverTool(tooltips=None))  
     
    colors=('aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen')
    ScalePhmi=math.pow(10,1)
    i=0
    for val,idx in zip(phmi_breakPtsNeg, plot_x):
        plot.line(idx,np.array(val)*ScalePhmi,line_color=colors[i])
        i+=1    
        
    show(plot)
    
#05-single landmarks pattern 无人车位置点与对应landmarks栅格图
#convert location and corresponding landmarks to raster data format using numpy.histogram2d
def colorMesh_phmi(landmarks,locations,targetPts_idx,Phmi):

0 Source : plots.py
with Apache License 2.0
from scaleoutsystems

    def make_netgraph_plot(self, df, df_nodes):
        """
        Create FEDn network visualization.

        :param df: pandas dataframe with defined edges
        :type df: pandas.Dataframe
        :param df_nodes:pandas dataframe with defined nodes
        :type df_nodes: pandas.Dataframe
        :return: Bokeh plot with the graph
        :rtype: bokeh.plotting.figure.Figure
        """

        if df.empty:
            #no combiners and thus no clients, plot only reducer
            plot = self.make_single_node_plot()
            return plot
           
        G = networkx.from_pandas_edgelist(df, 'source', 'target', create_using=networkx.Graph())
        degrees = dict(networkx.degree(G))
        networkx.set_node_attributes(G, name='degree', values=degrees)

        number_to_adjust_by = 20
        adjusted_node_size = dict([(node, degree + number_to_adjust_by) for node, degree in networkx.degree(G)])
        networkx.set_node_attributes(G, name='adjusted_node_size', values=adjusted_node_size)
        
        # community
        from networkx.algorithms import community
        communities = community.greedy_modularity_communities(G)
        # Create empty dictionaries
        modularity_class = {}
        modularity_color = {}
        # Loop through each community in the network
        for community_number, community in enumerate(communities):
            # For each member of the community, add their community number and a distinct color
            for name in community:
                modularity_class[name] = community_number
                modularity_color[name] = Spectral8[community_number]

        # Add modularity class and color as attributes from the network above
        networkx.set_node_attributes(G, modularity_class, 'modularity_class')
        networkx.set_node_attributes(G, modularity_color, 'modularity_color')

        node_role = {k:v for k,v in zip(df_nodes.id, df_nodes.role)}
        networkx.set_node_attributes(G, node_role, 'role')
        
        node_status = {k:v for k,v in zip(df_nodes.id, df_nodes.status)}
        networkx.set_node_attributes(G, node_status, 'status')

        node_name = {k:v for k,v in zip(df_nodes.id, df_nodes.name)}
        networkx.set_node_attributes(G, node_name, 'name')

        
        # Choose colors for node and edge highlighting
        node_highlight_color = 'white'
        edge_highlight_color = 'black'

        # Choose attributes from G network to size and color by — setting manual
        # size (e.g. 10) or color (e.g. 'skyblue') also allowed
        size_by_this_attribute = 'adjusted_node_size'
        color_by_this_attribute = 'modularity_color'

        # Establish which categories will appear when hovering over each node
        HOVER_TOOLTIPS = [
            ("Name", "@name"),
            ("Role", "@role"),
            ("Status", "@status"),
            ("Id", "@index"),
        ]
        # Create a plot — set dimensions, toolbar, and title
        plot = figure(tooltips=HOVER_TOOLTIPS,
                      tools="pan,wheel_zoom,save,reset", active_scroll='wheel_zoom',
                      width=725, height=460, sizing_mode='stretch_width',
                      x_range=Range1d(-1.5, 1.5), y_range=Range1d(-1.5, 1.5))

        # Create a network graph object
        # https://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.drawing.layout.spring_layout.html
        # if one like lock reducer add args: pos={'reducer':(0,1)}, fixed=['reducer']
        network_graph = from_networkx(G, networkx.spring_layout, scale=1, center=(0, 0), seed=45)

        # Set node sizes and colors according to node degree (color as category from attribute)
        network_graph.node_renderer.glyph = Circle(size=size_by_this_attribute, fill_color=color_by_this_attribute)
        # Set node highlight colors
        network_graph.node_renderer.hover_glyph = Circle(size=size_by_this_attribute, fill_color=node_highlight_color,
                                                         line_width=2)
        network_graph.node_renderer.selection_glyph = Circle(size=size_by_this_attribute,
                                                             fill_color=node_highlight_color, line_width=2)
        
        # Set edge opacity and width
        network_graph.edge_renderer.glyph = MultiLine(line_alpha=0.5, line_width=1)
        # Set edge highlight colors
        network_graph.edge_renderer.selection_glyph = MultiLine(line_color=edge_highlight_color, line_width=2)
        network_graph.edge_renderer.hover_glyph = MultiLine(line_color=edge_highlight_color, line_width=2)

        # Highlight nodes and edges
        network_graph.selection_policy = NodesAndLinkedEdges()
        network_graph.inspection_policy = NodesAndLinkedEdges()

        plot.renderers.append(network_graph)
        
        #Node labels, red if status is offline, green is active
        x, y = zip(*network_graph.layout_provider.graph_layout.values())
        node_names = list(G.nodes(data='name'))
        node_status = list(G.nodes(data='status'))

        idx_offline = []
        idx_online = []
        node_labels = []
        for e, n in enumerate(node_names):
            if node_status[e][1] == 'active':
                idx_online.append(e)
            else:
                idx_offline.append(e)
            node_labels.append(n[1])

        source_on = ColumnDataSource({'x': numpy.asarray(x)[idx_online], 'y': numpy.asarray(y)[idx_online], 'name': numpy.asarray(node_labels)[idx_online]})
        labels = LabelSet(x='x', y='y', text='name', source=source_on, background_fill_color='#4bbf73', text_font_size='15px',
                          background_fill_alpha=.7, x_offset=-20, y_offset=10)

        plot.renderers.append(labels)

        
        source_off = ColumnDataSource({'x': numpy.asarray(x)[idx_offline], 'y': numpy.asarray(y)[idx_offline], 'name': numpy.asarray(node_labels)[idx_offline]})
        labels = LabelSet(x='x', y='y', text='name', source=source_off, background_fill_color='#d9534f', text_font_size='15px',
                          background_fill_alpha=.7, x_offset=-20, y_offset=10)

        plot.renderers.append(labels)

        plot.axis.visible = False
        plot.grid.visible = False
        plot.outline_line_color = None
        return plot