#!/usr/bin/env python # coding: utf-8 # # Draft 2 # **Node and Edge Attributes** # In from_networkx, NetworkX's node/edge attributes are converted for GraphRenderer's node_renderer/edge_renderer. # For example, "Zachary's Karate Club graph" dataset has a node attribute named "club". It's possible to hover these information using the node attributes converted in from_networkx. Similarly, node/edge attributes can also be used for color information. # # Here’s a graph example that hovers node attributes and changes colors with edge attributes: # In[44]: import networkx as nx from bokeh.io import show, output_file, output_notebook, 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 # 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") print("G has node attributes. For example, {}".format(G.nodes[0])) print("G has edge attributes. For example, {}".format(G.edges[(0, 1)])) # 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) # This code will be change to "output_file("interactive_graphs.html") # output_file("interactive_graphs.html") output_notebook() show(plot) # In[ ]: