Beispiel #1
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 #2
0
def test_from_networkx_with_bad_attributes():
    G = nx.Graph()
    G.add_nodes_from([(0, {
        "index": "a",
        "attr_1": 10
    }), (1, {
        "index": "b",
        "attr_1": 20
    })])
    G.add_edges_from([[0, 1]])

    with pytest.warns(UserWarning):
        renderer = from_networkx(G, nx.circular_layout)
        assert renderer.node_renderer.data_source.data["index"] == [0, 1]
        assert renderer.node_renderer.data_source.data["attr_1"] == [10, 20]

    G = nx.Graph()
    G.add_nodes_from([0, 1])
    G.add_edges_from([(0, 1, {"start": "A", "attr_1": 10})])

    with pytest.warns(UserWarning):
        renderer = from_networkx(G, nx.circular_layout)
        assert renderer.edge_renderer.data_source.data["start"] == [0]
        assert renderer.edge_renderer.data_source.data["end"] == [1]
        assert renderer.edge_renderer.data_source.data["attr_1"] == [10]

    G = nx.Graph()
    G.add_nodes_from([0, 1])
    G.add_edges_from([(0, 1, {"end": "A", "attr_1": 10})])

    with pytest.warns(UserWarning):
        renderer = from_networkx(G, nx.circular_layout)
        assert renderer.edge_renderer.data_source.data["start"] == [0]
        assert renderer.edge_renderer.data_source.data["end"] == [1]
        assert renderer.edge_renderer.data_source.data["attr_1"] == [10]
Beispiel #3
0
def test_from_networkx_with_bad_attributes():
    G = nx.Graph()
    G.add_nodes_from([(0, {"index": "a", "attr_1": 10}),
                      (1, {"index": "b", "attr_1": 20})])
    G.add_edges_from([[0, 1]])

    with pytest.warns(UserWarning):
        renderer = from_networkx(G, nx.circular_layout)
        assert renderer.node_renderer.data_source.data["index"] == [0, 1]
        assert renderer.node_renderer.data_source.data["attr_1"] == [10, 20]

    G = nx.Graph()
    G.add_nodes_from([0, 1])
    G.add_edges_from([(0, 1, {"start": "A", "attr_1": 10})])

    with pytest.warns(UserWarning):
        renderer = from_networkx(G, nx.circular_layout)
        assert renderer.edge_renderer.data_source.data["start"] == [0]
        assert renderer.edge_renderer.data_source.data["end"] == [1]
        assert renderer.edge_renderer.data_source.data["attr_1"] == [10]

    G = nx.Graph()
    G.add_nodes_from([0, 1])
    G.add_edges_from([(0, 1, {"end": "A", "attr_1": 10})])

    with pytest.warns(UserWarning):
        renderer = from_networkx(G, nx.circular_layout)
        assert renderer.edge_renderer.data_source.data["start"] == [0]
        assert renderer.edge_renderer.data_source.data["end"] == [1]
        assert renderer.edge_renderer.data_source.data["attr_1"] == [10]
Beispiel #4
0
def test_from_networkx_deprecated() -> None:
    G = nx.Graph()
    G.add_nodes_from([0, 1, 2, 3])
    G.add_edges_from([[0, 1], [0, 2], [2, 3]])

    from bokeh.util.deprecation import BokehDeprecationWarning
    with pytest.warns(BokehDeprecationWarning):
        from_networkx(G, nx.circular_layout)
Beispiel #5
0
    def drawgraph(self, ds, filterMin, filterMax, layout):
        G = nx.Graph()  # create an empty graph with no nodes and no edges

        # nodes = []
        # for i in range(len(ds.getNodes())):
        #     nodes.append([])
        #     # print(ds.getNodes()[i].getName())
        #     for j in range(len(ds.getNodes())):
        #         nodes[i].append(ds.getNodes()[i].getLinks()[j][1])
        #         # print("   " + str(ds.getNodes()[i].getLinks()[j][1]))

        # ds.toMinSpanTree()
        nodes = ds.getDoubleList(filterMin, filterMax, False)

        x = filterMin

        adj = np.array(nodes)
        G = nx.from_numpy_matrix(adj)

        for i in range(len(G.node)):
            G.node[i]['name'] = ds.getNames()[i]
        #pos = nx.drawing.layout.circular_layout(G, 1, None, 2)

        #nx.draw_networkx(G, pos, with_labels=True)
        # pt.show()
        #plt.show()
        plot = Plot(plot_width=500, plot_height=500,
                    x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1))

        node_hover_tool = HoverTool(tooltips=[("Name of this node", "@name")])

        # plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool())
        plot.add_tools(node_hover_tool, TapTool(), BoxSelectTool(), BoxZoomTool(), UndoTool(), RedoTool(), SaveTool(),
                       ResetTool())
        plot.toolbar_location = 'left'
        if layout == 0:
            graph_renderer = from_networkx(G, nx.circular_layout, scale=1, center=(0, 0))
        elif layout == 1:
            graph_renderer = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0))
        else:
            graph_renderer = from_networkx(G, nx.random_layout)
        graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0])
        graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
        graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])

        graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=5)
        graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=5)
        graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=5)

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

        plot.renderers.append(graph_renderer)

        output_file("interactive_graphs.html")
        return plot
Beispiel #6
0
def test_from_networkx_errors_with_mixed_attributes():
    G = nx.Graph()
    G.add_nodes_from([(0, {"attr_1": [1, 2], "attr_2": 10}),
                      (1, {}),
                      (2, {"attr_1": 3, "attr_2": 30})])

    with pytest.raises(ValueError):
        from_networkx(G, nx.circular_layout)

    G = nx.Graph()
    G.add_edges_from([(0, 1, {"attr_1": [1, 11]}),
                      (0, 2, {"attr_1": 2, "attr_2": 10})])

    with pytest.raises(ValueError):
        from_networkx(G, nx.circular_layout)
Beispiel #7
0
def test_from_networkx_errors_with_mixed_attributes():
    G = nx.Graph()
    G.add_nodes_from([(0, {"attr_1": [1, 2], "attr_2": 10}),
                      (1, {}),
                      (2, {"attr_1": 3, "attr_2": 30})])

    with pytest.raises(ValueError):
        from_networkx(G, nx.circular_layout)

    G = nx.Graph()
    G.add_edges_from([(0, 1, {"attr_1": [1, 11]}),
                      (0, 2, {"attr_1": 2, "attr_2": 10})])

    with pytest.raises(ValueError):
        from_networkx(G, nx.circular_layout)
Beispiel #8
0
def plot_bqm(bqm):
    """Plot binary quadratic model as a labeled graph."""
    g = nx.Graph()
    g.add_nodes_from(bqm.variables)
    g.add_edges_from(bqm.quadratic)      
    plot_size = 400
    text_size = '16pt'
     
    graph = from_networkx(g, nx.spring_layout)
    graph.node_renderer.glyph = Circle(size=35, fill_color='purple', fill_alpha=0.25)
    graph.edge_renderer.glyph = MultiLine(line_alpha=0.8, line_width=2)
 
    pos = nx.spring_layout(g)
    data = {'xpos': [], 'ypos': [], 'label': []}
    for label, loc in pos.items():
        data['label'].append(label)
        data['xpos'].append(loc[0])
        data['ypos'].append(loc[1])
    labels = LabelSet(x='xpos', y='ypos', text='label', level='glyph', 
                      source=ColumnDataSource(data), x_offset=-1, y_offset=-1, 
                      text_color="blue", text_font_size='14pt', text_font_style='bold')    
    
    plot = Plot(plot_width=plot_size, plot_height=plot_size, x_range=Range1d(-1.3, 1.3), y_range=Range1d(-1.3, 1.3))
    plot.title.text = "BQM with {} nodes and {} edges".format(len(bqm), len(bqm.quadratic))
    
    tools = [WheelZoomTool(), ZoomInTool(), ZoomOutTool(), PanTool(), ResetTool()]
    plot.add_tools(*tools)
    plot.toolbar.active_scroll = tools[0]
    
    plot.renderers.append(graph)
    plot.add_layout(labels)
    plot.background_fill_color = "lightyellow"
        
    show(plot)
Beispiel #9
0
def render_network_graph(fig, datasource, df, glyph_obj):
    "Utility for plotting the network graph"
    #G_sub = G.subgraph(ids)
    #df_sub = df[df["id"].isin(ids)]
    G = nx.DiGraph()
    G.add_nodes_from(df.id.tolist())

    edge_list = df[df["infectionSource"].apply(
        lambda x: isinstance(x, int))].apply(
            lambda row: (row["id"], str(row["infectionSource"])),
            axis=1).tolist()

    G.add_edges_from(edge_list)
    positions = df.set_index("id")[["x", "y"]].apply(lambda row: {
        row.name: (row["x"], row["y"])
    },
                                                     axis=1).tolist()
    positions = {id_: pos for row in positions for id_, pos in row.items()}

    graph_renderer = graphs.from_networkx(G, positions,
                                          legend="case")  #, **kwds_network)
    graph_renderer.node_renderer.data_source.data = datasource.data

    graph_renderer.node_renderer.glyph = glyph_obj  #Circle(size=10, fill_color="colors")

    fig.renderers.append(graph_renderer)

    return graph_renderer.node_renderer.data_source
Beispiel #10
0
    def build_graph_renderer(graph, nodes, node_colors, node_sizes, node_scores, node_labels, levels):
        graph_renderer = from_networkx(graph, nx.kamada_kawai_layout)

        level_1 = list()
        for node in nodes:
            if node in levels[1]:
                level_1.append(1)
            else:
                level_1.append(0)

        graph_renderer.node_renderer.data_source.data['index'] = nodes
        graph_renderer.node_renderer.data_source.data['color'] = node_colors
        graph_renderer.node_renderer.data_source.data['size'] = node_sizes
        graph_renderer.node_renderer.data_source.data['root_score'] = node_scores[0]
        graph_renderer.node_renderer.data_source.data['usage_score'] = node_scores[1]
        graph_renderer.node_renderer.data_source.data['label'] = node_labels
        graph_renderer.node_renderer.data_source.data['level_1'] = level_1

        graph_renderer.node_renderer.glyph = Circle(size="size", fill_color="color")
        graph_renderer.node_renderer.selection_glyph = Circle(size="size", fill_color="color")
        graph_renderer.node_renderer.hover_glyph = Circle(size="size", fill_color="color")

        graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=5)
        graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=5)
        graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=5)

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

        return graph_renderer
def draw_network(t):

    # We could use figure here but don't want all the axes and titles
    plot = Plot(x_range=Range1d(-6, 6), y_range=Range1d(-6, 6))

    # Create a Bokeh graph from the NetworkX input using nx.spring_layout
    graph = from_networkx(graphs[t]["graph"],
                          nx.layout.fruchterman_reingold_layout,
                          scale=5,
                          center=(0, 0))
    plot.renderers.append(graph)

    graph.node_renderer.data_source.data['colors'] = graphs[t]["colors"]
    graph.node_renderer.data_source.data['sizes'] = graphs[t]["node_sizes"]
    graph.node_renderer.glyph = Circle(size='sizes', fill_color='colors')
    graph.edge_renderer.glyph = MultiLine(line_alpha=1.6, line_width=4)

    # green hover for both nodes and edges
    graph.node_renderer.hover_glyph = Circle(size='sizes',
                                             fill_color='#abdda4')
    graph.edge_renderer.hover_glyph = MultiLine(line_color='#abdda4',
                                                line_width=8)

    # When we hover over nodes, highlight adjecent edges too
    graph.inspection_policy = NodesAndLinkedEdges(
    )  # can we change this so edges can be hovered over too?

    TOOLTIPS = [
        ("Demand", "@demand"),
        ("Type", "@node_type"),
    ]

    plot.add_tools(HoverTool(tooltips=TOOLTIPS))

    return plot
Beispiel #12
0
def create_transactor_figure(G):
    plot = Plot(plot_width=800,
                plot_height=600,
                x_range=Range1d(-1.1, 1.1),
                y_range=Range1d(-1.1, 1.1))
    plot.title.text = "Transactor Visualization"

    plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool(),
                   WheelZoomTool(), PanTool())

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

    graph_renderer.node_renderer.glyph = Circle(size=4,
                                                fill_color=Spectral4[0])
    graph_renderer.node_renderer.selection_glyph = Circle(
        size=4, fill_color=Spectral4[2])
    graph_renderer.node_renderer.hover_glyph = Circle(size=4,
                                                      fill_color=Spectral4[1])

    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
                                                   line_alpha=0.8,
                                                   line_width=3)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(
        line_color=Spectral4[2], line_width=3)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(
        line_color=Spectral4[1], line_width=3)

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

    plot.renderers.append(graph_renderer)

    return plot
def test_from_networkx_with_sequence_attributes(typ):
    G = nx.Graph()
    G.add_nodes_from([(0, {
        "attr_1": typ([1, 2]),
        "attr_2": 10
    }), (1, {}), (2, {
        "attr_1": typ([3]),
        "attr_2": 30
    })])
    G.add_edges_from([(0, 1, {
        "attr_1": typ([1, 11])
    }), (0, 2, {
        "attr_1": typ([2, 22]),
        "attr_2": 10
    })])

    renderer = from_networkx(G, nx.circular_layout)

    assert renderer.node_renderer.data_source.data["index"] == [0, 1, 2]
    assert renderer.node_renderer.data_source.data["attr_1"] == [[1, 2], [],
                                                                 [3]]
    assert renderer.node_renderer.data_source.data["attr_2"] == [10, None, 30]

    assert renderer.edge_renderer.data_source.data["start"] == [0, 0]
    assert renderer.edge_renderer.data_source.data["end"] == [1, 2]
    assert renderer.edge_renderer.data_source.data["attr_1"] == [[1, 11],
                                                                 [2, 22]]
    assert renderer.edge_renderer.data_source.data["attr_2"] == [None, 10]
Beispiel #14
0
def draw_graph(plot, G):
    plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool())
    graph = from_networkx(G,
                          nx.spring_layout,
                          pos=node_positions,
                          fixed=node_positions.keys())

    graph.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0])
    graph.node_renderer.selection_glyph = Circle(size=15,
                                                 fill_color=Spectral4[2])
    graph.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])

    graph.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
                                          line_alpha=0.8,
                                          line_width=5)
    graph.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2],
                                                    line_width=5)
    graph.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1],
                                                line_width=5)

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

    plot.renderers.append(graph)
    return plot
Beispiel #15
0
def subnetwork_depth_generator(top_n_nodes, depth=2):
    with open(r"./flaskexample/full_network_with_titles.pickle",
              "rb") as input_file:
        full_network_with_titles = pickle.load(input_file)
    sub_network_set = {
        key
        for node in top_n_nodes for key in nx.single_source_shortest_path(
            full_network_with_titles, node, cutoff=depth).keys()
    }
    sub_network_with_titles = full_network_with_titles.subgraph(
        sub_network_set)
    # Show with Bokeh
    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 = "Citation Network"
    node_hover_tool = HoverTool(tooltips=[("Title", "@title")])
    plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool())
    # plot.add_tools(BoxZoomTool(), ResetTool())
    graph_renderer = from_networkx(sub_network_with_titles,
                                   nx.spring_layout,
                                   scale=1,
                                   center=(0, 0))
    graph_renderer.node_renderer.glyph = Circle(size=4,
                                                fill_color=Spectral4[0])
    # graph_renderer.edge_renderer.glyph = MultiLine(line_color="edge_color", line_alpha=0.8, line_width=1)
    plot.renderers.append(graph_renderer)
    return (plot)
def graphNetwork(data, tags):
    G = nx.from_numpy_matrix(data)
    graph_plot = Plot(plot_width=800,
                      plot_height=800,
                      x_range=Range1d(-1.1, 1.1),
                      y_range=Range1d(-1.1, 1.1))
    graph_plot.title.text = "Graph.\nTotal Nodes: %i\nTotal Edges: %i" % (
        G.number_of_nodes(), G.number_of_edges())

    node_hover_tool = HoverTool(tooltips=[("hashtag", "@hashtag")])
    graph_plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool(),
                         WheelZoomTool(), BoxSelectTool())

    graph_renderer = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0))
    graph_renderer.node_renderer.glyph = Circle(size=15, fill_color='#277bb6')
    graph_renderer.node_renderer.hover_glyph = Circle(size=18,
                                                      fill_color='#E84A5F')
    graph_renderer.edge_renderer.glyph = MultiLine(line_color="gray",
                                                   line_alpha=0.8,
                                                   line_width=0.5)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color='#e09e8f',
                                                         line_width=3)
    graph_renderer.inspection_policy = NodesAndLinkedEdges()
    graph_renderer.selection_policy = EdgesAndLinkedNodes()
    graph_renderer.node_renderer.data_source.data['hashtag'] = tags

    graph_plot.renderers.append(graph_renderer)

    output_file("interactive_graphs.html")

    show(graph_plot)
Beispiel #17
0
def create_cit_map(nodes, edges):

    G = nx.DiGraph()

    G.add_nodes_from(nodes)

    G.add_edges_from(edges)

    plot = Plot(plot_width=800, plot_height=800, x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))
    plot.title.text = ""

    graph_renderer = from_networkx(G, nx.kamada_kawai_layout, scale=1)

    graph_renderer.node_renderer.glyph = Circle(size=15)
    graph_renderer.node_renderer.selection_glyph = Circle(size=15)
    graph_renderer.node_renderer.hover_glyph = Circle(size=15)

    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=5)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(line_width=5)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(line_width=5)

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

    pos = graph_renderer.layout_provider.graph_layout
    x,y=zip(*pos.values())
    source = ColumnDataSource({'x':x,'y':y,'names': nodes})
    labels = LabelSet(x='x', y='y', text='names', source=source, level='glyph', x_offset=5, y_offset=5)

    plot.renderers.append(labels)

    plot.renderers.append(graph_renderer)
    #plot.add_layout(labels)
    output_file("interactive_graphs.html")
    show(plot)
Beispiel #18
0
def render_karate_graph():
    G = nx.karate_club_graph()

    SAME_CLUB_COLOR, DIFFERENT_CLUB_COLOR = "black", "red"
    edge_attrs = {}
    for start_node, end_node, _ in G.edges(data=True):
        edge_color = SAME_CLUB_COLOR if G.nodes[start_node][
            "club"] == G.nodes[end_node]["club"] else DIFFERENT_CLUB_COLOR
        edge_attrs[(start_node, end_node)] = edge_color

    nx.set_edge_attributes(G, edge_attrs, "edge_color")

    # Show with Bokeh
    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 = "Graph Interaction Demonstration"

    node_hover_tool = HoverTool(
        tooltips=[("index", "@index"), ("club", "@club")])
    plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool())

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

    graph_renderer.node_renderer.glyph = Circle(
        size=15, fill_color=Spectral4[0])
    graph_renderer.edge_renderer.glyph = MultiLine(
        line_color="edge_color", line_alpha=0.8, line_width=1)
    plot.renderers.append(graph_renderer)
    return plot
Beispiel #19
0
def create_graph_rendrer(threshold, df, graph_df):
    plot_new = Plot(plot_width=1100,
                    plot_height=800,
                    x_range=Range1d(-1.1, 1.1),
                    y_range=Range1d(-1.1, 1.1))
    plot_new.title.text = "Dash-Graph"

    color_dict = {}

    for i in range(1, df['UserID'].max() + 1):
        color_dict[i] = df.groupby('UserID').groups[i].size * 1.9

    pal_hex_lst = bokeh.palettes.viridis(21)
    mapper = LinearColorMapper(palette=pal_hex_lst, low=0, high=21)

    G = create_graph(graph_df, threshold, True)

    # add graph's attributes
    node_size = {k: ((5 * v) + 5) for k, v in G.degree()}
    nx.set_node_attributes(G, color_dict, 'node_color')
    nx.set_node_attributes(G, node_size, 'node_size')
    graph_renderer = from_networkx(G, nx.spring_layout)
    graph_renderer.node_renderer.glyph = Circle(size='node_size',
                                                fill_color={
                                                    'field': 'node_color',
                                                    'transform': mapper
                                                })
    graph_renderer.edge_renderer.glyph = MultiLine(line_color="black",
                                                   line_alpha=0.8,
                                                   line_width=0.5)
    graph_renderer.selection_policy = NodesAndLinkedEdges()

    plot.renderers.append(graph_renderer)
Beispiel #20
0
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))
Beispiel #21
0
def test_html(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')
    G = nx.karate_club_graph()
    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 = "Graph Interaction Demonstration"

    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.glyph = Circle(size=15, fill_color=Spectral4[0])
    graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
    graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])

    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=5)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=5)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=5)

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

    plot.renderers.append(graph_renderer)

    output_file("interactive_graphs.html")
    show(plot)
Beispiel #22
0
def main() -> None:
    """メイン処理

    Note:
        from_networkx ではランダム値によりグラフ中のノード位置が決定する。
        そのため、 numpy の random seed を固定することで、毎回同じ形のグラフが出力されるようにする。
    """
    np.random.seed(0)

    graph = nx.karate_club_graph()
    graph = bkhgraphs.from_networkx(graph,
                                    nx.spring_layout,
                                    scale=2,
                                    center=(0, 0))

    # グラフ初期設定
    p = bkhplotting.figure(
        tools=("pan,box_zoom,lasso_select,box_select,poly_select"
               ",tap,wheel_zoom,reset,save,zoom_in"),
        title="Networkx Integration Demonstration",
        x_range=(-2.1, 2.1),
        y_range=(-2.1, 2.1),
    )
    p.renderers.append(graph)

    # レイアウト
    layout = bkhlayouts.layout([p], sizing_mode="stretch_both")

    bkhio.curdoc().add_root(layout)
Beispiel #23
0
    def get_graph(self):

        start = self.data['Start']
        end = self.data['End']
        fl = self.data['Index']
        fio = self.data['FIO']
        node_indices = end.append(pd.Series(pd.Series.unique(self.data['Start'])), ignore_index=True)
        #fl = pd.Series.unique(self.data['Index'])
        #fl = self.data['Index']
        #edges = zip(start, end)
        edges =[]
        for i in range(len(start)):
                edges.append(tuple([start[i], end[i], {'OGRNIP': str(fl[i]) + " - " + str(fio[i])}]))
        G = nx.Graph()
        G.add_nodes_from(node_indices)
        G.add_edges_from(edges)
        #print(G.adj.items())
        #print(G.edges.data())
        ogrns =[]
        for item in G.edges.data():
            #print(item[2]['OGRNIP'])
            ogrns.append(item[2]['OGRNIP'])
        tooltips=[
            #("index", "$index"),
            #("(x,y)", "($x, $y)"),
            ("1 - ОГРН", "@start"),
            ("2 - ОГРН", "@end"),
            ("ФЛ", "@OGRNIP"),
            #("Моя подсказка", "@end"),
        ]
        # hover = HoverTool(tooltips=tooltips)

        p = figure(plot_width=self.width, plot_height=self.height, x_range=(-3.1, 3.1), y_range=(-3.1, 3.1),
                   x_axis_type=None, y_axis_type=None, tools=[],
                   min_border=0, outline_line_color="white")

        # p.add_tools(WheelZoomTool())
        # p.add_tools(PanTool())
        p.add_tools(HoverTool(tooltips=tooltips), TapTool(), BoxSelectTool(), WheelZoomTool(), PanTool())

        #graph = from_networkx(G, nx.circular_layout, scale=1, center=(0, 0))
        graph = from_networkx(G, nx.spring_layout, scale=2, center=(0, 0))
        graph.node_renderer.glyph = Circle(size=5, fill_color="gray")
        graph.node_renderer.hover_glyph = Circle(size=5, fill_color="red")
        graph.node_renderer.selection_glyph = Circle(size=5, fill_color="green")

        graph.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=1)
        graph.edge_renderer.selection_glyph = MultiLine(line_color="gray", line_width=1)
        graph.edge_renderer.hover_glyph = MultiLine(line_color="gray", line_width=1)

        graph.selection_policy = NodesAndLinkedEdges()
        graph.inspection_policy = EdgesAndLinkedNodes()
        # print(graph.node_renderer.data_source.data)
        # print(graph.edge_renderer.data_source.data)
        graph.edge_renderer.data_source.data['OGRNIP'] = ogrns
        #print(graph.edge_renderer.data_source.data)
        #print(graph.node_renderer.data_source.data)
        p.renderers.append(graph)

        return p
def plot_overlap_graph(level, graph):
    plot = Plot(plot_width=600,
                plot_height=450,
                x_range=Range1d(-1.1, 1.1),
                y_range=Range1d(-1.1, 1.1),
                toolbar_location="below")
    plot.title.text = f"{level.title()}"
    plot.title.align = 'center'
    plot.title.text_font_size = '16pt'

    TOOLTIPS = """
            <div>
                <span style="font-size: 18px; font-weight: bold;">Name: @index</span>
            </div>
            <div>
                <span style="font-size: 18px; font-weight: bold; color: @colors;">Region: @region</span>
            </div>
        """
    node_hover_tool = HoverTool(tooltips=TOOLTIPS)
    plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool(),
                   PointDrawTool())

    graph_renderer = from_networkx(graph,
                                   nx.spring_layout,
                                   scale=1,
                                   center=(0, 0))

    if len(graph.nodes) > 0:
        graph_renderer.node_renderer.glyph = Circle(size=6,
                                                    fill_color="colors")
        graph_renderer.edge_renderer.glyph = MultiLine(line_color="edge_color",
                                                       line_alpha=0.8,
                                                       line_width=1.5)
    plot.renderers.append(graph_renderer)
    return plot
Beispiel #25
0
def NLD_pocessing_graph(g, weights, colors, layout):
    graph = from_networkx(g, layout, scale=1, center=(0, 0))

    # nodes and egdes attributes
    graph.node_renderer.data_source.data['degree'] = list(zip(*g.degree))[1]
    graph.edge_renderer.data_source.data['weight'] = weights
    graph.edge_renderer.data_source.add(colors, 'color')

    graph.node_renderer.glyph = Circle(size='nodesize',
                                       fill_alpha=0.8,
                                       fill_color='royalblue')
    graph.node_renderer.selection_glyph = Circle(size=10,
                                                 fill_alpha=0.8,
                                                 fill_color='red')
    graph.node_renderer.hover_glyph = Circle(size=10,
                                             fill_alpha=0.8,
                                             fill_color='yellow')

    graph.edge_renderer.glyph = MultiLine(line_width=2.5,
                                          line_alpha=0.8,
                                          line_color='color')
    graph.edge_renderer.selection_glyph = MultiLine(line_width=2.5,
                                                    line_alpha=0.8,
                                                    line_color='red')
    graph.edge_renderer.hover_glyph = MultiLine(line_width=2.5,
                                                line_alpha=0.8,
                                                line_color='yellow')
    graph.edge_renderer.glyph.line_width = {'field': 'weight'}

    graph.selection_policy = NodesAndLinkedEdges()
    graph.inspection_policy = NodesAndLinkedEdges()

    return graph
Beispiel #26
0
def plot_labelled_bokeh_ni(G, id, filename="test.html"):
    plot = figure(title="Title",
                  tools="",
                  x_range=(-1.5, 1.5),
                  y_range=(-1.5, 1.5),
                  toolbar_location=None)
    graph = from_networkx(G, nx.spring_layout)
    plot.renderers.append(graph)

    x, y = zip(*graph.layout_provider.graph_layout.values())

    node_labels = nx.get_node_attributes(G, 'hostname')

    source = ColumnDataSource({
        'x':
        x,
        'y':
        y,
        'label': [node_labels[id[i]] for i in range(len(x))]
    })

    labels = LabelSet(x='x',
                      y='y',
                      text='label',
                      source=source,
                      background_fill_color='white')

    plot.renderers.append(labels)

    save(plot, filename)
Beispiel #27
0
    def network_dynamic(self, df):
        graph = nx.from_pandas_edgelist(df, 'word1', 'word2', 'count')

        # Establish which categories will appear when hovering over each node
        HOVER_TOOLTIPS = [("", "@index")]

        # Create a plot — set dimensions, toolbar, and title
        plot = figure(tooltips=HOVER_TOOLTIPS,
                      tools="pan,wheel_zoom,save,reset",
                      active_scroll='wheel_zoom',
                      x_range=Range1d(-10.1, 10.1),
                      y_range=Range1d(-10.1, 10.1),
                      plot_width=1000,
                      title='')

        # Create a network graph object with spring layout
        network_graph = from_networkx(graph,
                                      nx.spring_layout,
                                      scale=10,
                                      center=(0, 0))

        # Set node size and color
        network_graph.node_renderer.glyph = Circle(size=15,
                                                   fill_color='skyblue')

        # Set edge opacity and width
        network_graph.edge_renderer.glyph = MultiLine(line_alpha=0.5,
                                                      line_width=1)

        #Add network graph to the plot
        plot.renderers.append(network_graph)

        script, div = components(plot)
        return script, div
Beispiel #28
0
def bokeh(G, node_color=None, node_label=None, node_size=100, node_size_scale=[25,200], alpha=0.8, font_size=18, cmap='Set1', width=40, height=30, pos=None, filename=None, title=None, methodtype='default', verbose=3):
    import networkx as nx
    from bokeh.io import show, output_file
    from bokeh.models import Plot, Range1d, MultiLine, Circle, HoverTool, BoxZoomTool, ResetTool
    from bokeh.models.graphs import from_networkx
    from bokeh.palettes import Spectral4
    
    SAME_CLUB_COLOR, DIFFERENT_CLUB_COLOR = "black", "red"
    edge_attrs = {}
    
    for start_node, end_node, _ in G.edges(data=True):
        edge_color = SAME_CLUB_COLOR if G.nodes[start_node]["club"] == G.nodes[end_node]["club"] else DIFFERENT_CLUB_COLOR
        edge_attrs[(start_node, end_node)] = edge_color
    
    nx.set_edge_attributes(G, edge_attrs, "edge_color")
    
    # Show with Bokeh
    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 = "Graph Interaction Demonstration"
    
    node_hover_tool = HoverTool(tooltips=[("index", "@index"), ("club", "@club")])
    plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool())
    
    graph_renderer = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0))
    
    graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0])
    graph_renderer.edge_renderer.glyph = MultiLine(line_color="edge_color", line_alpha=0.8, line_width=1)
    plot.renderers.append(graph_renderer)
    
    output_file("interactive_graphs.html")
    show(plot)
    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
def plot_subgraph(  onto_graph:nx.Graph, node_subset:Union[List[str],Set[str]],
                    in_IPython:bool=False):
    """
    """
    G = onto_graph.subgraph(node_subset)
    # Show with Bokeh
    plot = Plot(plot_width=1600, plot_height=800,
                x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1))

    plot.title.text = "Graph Interaction Demonstration"

    node_hover_tool = HoverTool(tooltips=[("index", "@index"), ("club", "@club")])
    plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool(), TapTool(), BoxSelectTool(), PanTool())

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

    graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0])
    graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
    graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])

    graph_renderer.edge_renderer.glyph = MultiLine(line_alpha=0.8, line_width=1)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=5)
    #graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=5)

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


    plot.renderers.append(graph_renderer)

    #output_file("interactive_graphs.html")
    if in_IPython: output_notebook()

    show(plot)
Beispiel #31
0
def test_from_networkx_with_attributes():
    G = nx.Graph()
    G.add_nodes_from([(0, {
        "attr_1": "a",
        "attr_2": 10
    }), (1, {
        "attr_1": "b"
    }), (2, {
        "attr_1": "c",
        "attr_2": 30
    })])
    G.add_edges_from([(0, 1, {
        "attr_1": "A"
    }), (0, 2, {
        "attr_1": "B",
        "attr_2": 10
    })])

    renderer = from_networkx(G, nx.circular_layout)

    assert renderer.node_renderer.data_source.data["index"] == [0, 1, 2]
    assert renderer.node_renderer.data_source.data["attr_1"] == ["a", "b", "c"]
    assert renderer.node_renderer.data_source.data["attr_2"] == [10, None, 30]

    assert renderer.edge_renderer.data_source.data["start"] == [0, 0]
    assert renderer.edge_renderer.data_source.data["end"] == [1, 2]
    assert renderer.edge_renderer.data_source.data["attr_1"] == ["A", "B"]
    assert renderer.edge_renderer.data_source.data["attr_2"] == [None, 10]
Beispiel #32
0
def create_graph(layout_func,
                 inspection_policy=None,
                 selection_policy=None,
                 **kwargs):

    plot = Plot(plot_width=400,
                plot_height=400,
                x_range=Range1d(-1.1, 1.1),
                y_range=Range1d(-1.1, 1.1))
    graph_renderer = from_networkx(G, layout_func, **kwargs)

    graph_renderer.node_renderer.glyph = Circle(size=15,
                                                fill_color=Spectral4[0])
    graph_renderer.node_renderer.selection_glyph = Circle(
        size=15, fill_color=Spectral4[2])
    graph_renderer.node_renderer.hover_glyph = Circle(size=15,
                                                      fill_color=Spectral4[1])

    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC",
                                                   line_alpha=0.8,
                                                   line_width=5)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(
        line_color=Spectral4[2], line_width=5)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(
        line_color=Spectral4[1], line_width=5)

    graph_renderer.inspection_policy = inspection_policy
    graph_renderer.selection_policy = selection_policy

    plot.renderers.append(graph_renderer)

    return plot
Beispiel #33
0
def test_from_networkx_method_with_kwargs():
    G=nx.Graph()
    G.add_nodes_from([0,1,2,3])
    G.add_edges_from([[0,1], [0,2], [2,3]])

    renderer = from_networkx(G, nx.circular_layout, scale=2)

    gl = renderer.layout_provider.graph_layout
    assert set(gl.keys()) == set([0,1,2,3])
    assert_allclose(gl[0], np.array([2., 0.]), atol=1e-7)
Beispiel #34
0
def test_from_networkx_method():
    G=nx.Graph()
    G.add_nodes_from([0,1,2,3])
    G.add_edges_from([[0,1], [0,2], [2,3]])

    renderer = from_networkx(G, nx.circular_layout)
    assert renderer.node_renderer.data_source.data["index"] == [0,1,2,3]
    assert renderer.edge_renderer.data_source.data["start"] == [0,0,2]
    assert renderer.edge_renderer.data_source.data["end"] == [1,2,3]

    gl = renderer.layout_provider.graph_layout
    assert set(gl.keys()) == set([0,1,2,3])
    assert_allclose(gl[0], np.array([1., 0.]), atol=1e-7)
Beispiel #35
0
def test_from_networkx_with_missing_layout():
    G = nx.Graph()
    G.add_nodes_from([0, 1, 2])
    G.add_edges_from([[0, 1], [0, 2]])

    missing_fixed_layout = {0: [0, 1],
                            1: [-1, 0]}

    with pytest.warns(UserWarning):
        renderer = from_networkx(G, missing_fixed_layout)
        gl = renderer.layout_provider.graph_layout
        assert set(gl.keys()) == set([0, 1])
        assert renderer.layout_provider.graph_layout[0] == missing_fixed_layout[0]
        assert renderer.layout_provider.graph_layout[1] == missing_fixed_layout[1]
Beispiel #36
0
def test_from_networkx_with_sequence_attributes(typ):
    G = nx.Graph()
    G.add_nodes_from([(0, {"attr_1": typ([1, 2]), "attr_2": 10}),
                      (1, {}),
                      (2, {"attr_1": typ([3]), "attr_2": 30})])
    G.add_edges_from([(0, 1, {"attr_1": typ([1, 11])}),
                      (0, 2, {"attr_1": typ([2, 22]), "attr_2": 10})])

    renderer = from_networkx(G, nx.circular_layout)

    assert renderer.node_renderer.data_source.data["index"] == [0, 1, 2]
    assert renderer.node_renderer.data_source.data["attr_1"] == [[1, 2], [], [3]]
    assert renderer.node_renderer.data_source.data["attr_2"] == [10, None, 30]

    assert renderer.edge_renderer.data_source.data["start"] == [0, 0]
    assert renderer.edge_renderer.data_source.data["end"] == [1, 2]
    assert renderer.edge_renderer.data_source.data["attr_1"] == [[1, 11], [2, 22]]
    assert renderer.edge_renderer.data_source.data["attr_2"] == [None, 10]
Beispiel #37
0
def test_from_networkx_with_attributes():
    G = nx.Graph()
    G.add_nodes_from([(0, {"attr_1": "a", "attr_2": 10}),
                      (1, {"attr_1": "b"}),
                      (2, {"attr_1": "c", "attr_2": 30})])
    G.add_edges_from([(0, 1, {"attr_1": "A"}),
                      (0, 2, {"attr_1": "B", "attr_2": 10})])

    renderer = from_networkx(G, nx.circular_layout)

    assert renderer.node_renderer.data_source.data["index"] == [0, 1, 2]
    assert renderer.node_renderer.data_source.data["attr_1"] == ["a", "b", "c"]
    assert renderer.node_renderer.data_source.data["attr_2"] == [10, None, 30]

    assert renderer.edge_renderer.data_source.data["start"] == [0, 0]
    assert renderer.edge_renderer.data_source.data["end"] == [1, 2]
    assert renderer.edge_renderer.data_source.data["attr_1"] == ["A", "B"]
    assert renderer.edge_renderer.data_source.data["attr_2"] == [None, 10]
Beispiel #38
0
def test_from_networkx_fixed_layout():
    G = nx.Graph()
    G.add_nodes_from([0, 1, 2])
    G.add_edges_from([[0, 1], [0, 2]])

    fixed_layout = {0: [0, 1],
                    1: [-1, 0],
                    2: [1, 0]}

    renderer = from_networkx(G, fixed_layout)
    assert renderer.node_renderer.data_source.data["index"] == [0, 1, 2]
    assert renderer.edge_renderer.data_source.data["start"] == [0, 0]
    assert renderer.edge_renderer.data_source.data["end"] == [1, 2]

    gl = renderer.layout_provider.graph_layout
    assert set(gl.keys()) == set([0, 1, 2])
    assert renderer.layout_provider.graph_layout[0] == fixed_layout[0]
    assert renderer.layout_provider.graph_layout[1] == fixed_layout[1]
    assert renderer.layout_provider.graph_layout[2] == fixed_layout[2]
Beispiel #39
0
def create_graph(layout_func, inspection_policy=None, selection_policy=None, **kwargs):

    plot = Plot(plot_width=400, plot_height=400,
                x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1))
    graph_renderer = from_networkx(G, layout_func, **kwargs)

    graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0])
    graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
    graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])

    graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=5)
    graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=5)
    graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=5)

    graph_renderer.inspection_policy = inspection_policy
    graph_renderer.selection_policy = selection_policy

    plot.renderers.append(graph_renderer)

    return plot
from bokeh.palettes import Spectral4

# Prepare Data
G = nx.karate_club_graph()

SAME_CLUB_COLOR, DIFFERENT_CLUB_COLOR = "black", "red"
edge_attrs = {}

for start_node, end_node, _ in G.edges(data=True):
    edge_color = SAME_CLUB_COLOR if G.nodes[start_node]["club"] == G.nodes[end_node]["club"] else DIFFERENT_CLUB_COLOR
    edge_attrs[(start_node, end_node)] = edge_color

nx.set_edge_attributes(G, edge_attrs, "edge_color")

# Show with Bokeh
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 = "Graph Interaction Demonstration"

node_hover_tool = HoverTool(tooltips=[("index", "@index"), ("club", "@club")])
plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool())

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

graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0])
graph_renderer.edge_renderer.glyph = MultiLine(line_color="edge_color", line_alpha=0.8, line_width=1)
plot.renderers.append(graph_renderer)

output_file("interactive_graphs.html")
show(plot)
import networkx as nx

from bokeh.io import show, output_file
from bokeh.models import Plot, Range1d, MultiLine, Circle, HoverTool, TapTool, BoxSelectTool
from bokeh.models.graphs import from_networkx, NodesAndLinkedEdges, EdgesAndLinkedNodes
from bokeh.palettes import Spectral4

G=nx.karate_club_graph()

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 = "Graph Interaction Demonstration"

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.glyph = Circle(size=15, fill_color=Spectral4[0])
graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])

graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=5)
graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=5)
graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=5)

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

plot.renderers.append(graph_renderer)

output_file("interactive_graphs.html")