def build_graph_renderer(graph, nodes, node_colors, node_sizes, node_scores, node_labels): graph_renderer = from_networkx(graph, nx.kamada_kawai_layout) 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.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 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 create_graph(): #Find the layout and color choice if radio_layout.active == 0: lay = 'WDegreepos' elif radio_layout.active == 1: lay = 'bwcentralpos' else: lay = 'ccentralpos' if radio_color.active == 0: col = 'DegCol' elif radio_color.active == 1: col = 'Colbw' elif radio_color.active == 2: col = 'friend' elif radio_color.active == 3: col = 'reviewcount' else: col = 'comprank' # Create Network view graph = GraphRenderer() graph.node_renderer.data_source.data = nodes_df(G, col) graph.edge_renderer.data_source.data = edges_df(G) graph.node_renderer.glyph = Circle(size='size', fill_color='Col', line_color="black", line_alpha=0.1, fill_alpha=1) graph.edge_renderer.glyph = MultiLine(line_alpha='alpha', line_width=0.1, line_color="#d8b7a4") graph_layout = dict(nx.get_node_attributes(G, lay)) graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout) # Glyph properties on selection graph.selection_policy = NodesAndLinkedEdges() graph.inspection_policy = EdgesAndLinkedNodes() graph.node_renderer.selection_glyph = Circle(size=12, fill_color='#0A5EB6', line_color="#002217") graph.edge_renderer.selection_glyph = MultiLine(line_color="#2972BE", line_width=0.5, line_alpha=0.4) # Adding graph to plot plot = figure(title="Yelp Users Layout", x_range=(-6.5, 6.5), y_range=(-6.5, 6.5), plot_width=525, plot_height=525, toolbar_location="above") plot.outline_line_alpha = 0 plot.xgrid.grid_line_color = None plot.ygrid.grid_line_color = None plot.xaxis.visible = False plot.yaxis.visible = False plot.renderers.append(graph) # Adding graph return row(plot)
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)
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)
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=3, line_alpha=0.8, line_color='color') graph.edge_renderer.selection_glyph = MultiLine(line_width=4, line_alpha=0.8, line_color='red') graph.edge_renderer.hover_glyph = MultiLine(line_width=4, 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
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(-.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 define_edges(self): start = [] end = [] for key in self.vertices: # Make a copy of the edges in roder to preserve the integrity of # the Graph connected_nodes = self.graph.vertices[str(key)].copy() # If there are Edges for the current looped Vertex if len(connected_nodes): for i in range(len(connected_nodes)): start.append(key) # Add node end.append(int(connected_nodes.pop())) # Add related edge # print(start) # print(end) # print(self.graph.vertices[str(key)]) color = ['#111111']*len(start) self.bokeh_graph.edge_renderer.data_source.data = dict( start=start, end=end, ) self.bokeh_graph.edge_renderer.glyph = MultiLine( line_color="#CCCCCC", line_alpha=0.8, line_width=1) self.bokeh_graph.edge_renderer.selection_glyph = MultiLine( line_color=Spectral4[2], line_width=3) self.bokeh_graph.edge_renderer.hover_glyph = MultiLine( line_color=Spectral4[1], line_width=3) print(self.bokeh_graph.edge_renderer.data_source.data.keys())
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 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)
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)
def create_graph(layout_func, inspection_policy=None, selection_policy=None, **kwargs): plot = Plot(width=400, 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) if inspection_policy is not None: graph_renderer.inspection_policy = inspection_policy if selection_policy is not None: graph_renderer.selection_policy = selection_policy plot.renderers.append(graph_renderer) return plot
def NLD_FD_pocessing_graph(g, weights, colors): degree_sequence = sorted([d for n, d in g.degree()], reverse=True) magicnumber = (g.number_of_nodes() / degree_sequence[0]**2) r = 2.2 / magicnumber my_points = nx.fruchterman_reingold_layout(g, k=r, iterations=100) graph_fd = from_networkx(g, my_points) #posxy=nx.fruchterman_reingold_layout(g) #for i in range(len(posxy()): # posxy #radii = np.random.random(size=N) * 1.5 my_colors = [] for key, value in my_points.items(): x = value[0] + 1.0 # x = -1 .. +1, so move to 0 ... 2 y = value[1] + 1.0 # y = -1 .. +1, so move to 0 ... 2 my_colors.append("#%02x%02x%02x" % (int(50 + 100 * x), int(30 + 100 * y), 150)) # nodes and egdes attributes graph_fd.node_renderer.data_source.data['degree'] = list(zip(*g.degree))[1] graph_fd.node_renderer.data_source.data['degree2'] = [ sqrt(x + 6) for x in graph_fd.node_renderer.data_source.data['degree'] ] graph_fd.node_renderer.data_source.data['nodessize'] = [ x * 115 / (sqrt(g.number_of_nodes() + (np.mean(degree_sequence)))) for x in graph_fd.node_renderer.data_source.data['degree2'] ] graph_fd.node_renderer.data_source.data['my_fill_color'] = my_colors graph_fd.edge_renderer.data_source.data['weight'] = weights graph_fd.edge_renderer.data_source.add(colors, 'color') graph_fd.node_renderer.glyph = Circle(size="nodesize", fill_color='my_fill_color', fill_alpha=0.85) graph_fd.node_renderer.selection_glyph = Circle(size=15, fill_alpha=0.8, fill_color='red') graph_fd.node_renderer.hover_glyph = Circle(size=15, fill_alpha=0.8, fill_color='yellow') graph_fd.edge_renderer.glyph = MultiLine(line_width=2.5, line_alpha=0.8, line_color='color') graph_fd.edge_renderer.selection_glyph = MultiLine(line_width=2.5, line_alpha=0.8, line_color='red') graph_fd.edge_renderer.hover_glyph = MultiLine(line_width=2.5, line_alpha=0.8, line_color='yellow') graph_fd.edge_renderer.glyph.line_width = {'field': 'weight'} graph_fd.selection_policy = NodesAndLinkedEdges() graph_fd.inspection_policy = NodesAndLinkedEdges() return graph_fd
def graphNetwork(adjm, data): G = nx.from_numpy_matrix(adjm) data['degree'] = list(dict(G.degree).values()) subgraphs = getSubgraphs(G) subgraphs = data.join(subgraphs.set_index('nodes')) subgraphs['subsets'] = adjm.sum(axis=0) 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\t Total subgraphs:%i" % ( G.number_of_nodes(), G.number_of_edges(), len(subgraphs.subgraph.unique())) node_hover_tool = HoverTool( tooltips=[("hashtag", "@hashtag"), ("freq", "@frequency"), ( 'degree', '@degree'), ('subsets', '@subsets'), ('subgraph', '@subgraph'), ('ix', '@ix')]) graph_plot.add_tools(node_hover_tool, BoxZoomTool(), ResetTool(), WheelZoomTool()) graph_renderer = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0)) graph_renderer.node_renderer.glyph = Circle(size=18, fill_color='#277bb6') graph_renderer.node_renderer.hover_glyph = Circle(size=18, fill_color='#E84A5F') graph_renderer.node_renderer.glyph.properties_with_values() graph_renderer.edge_renderer.glyph = MultiLine(line_color="gray", line_alpha=0.7, line_width=0.3) graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color='#e09e8f', line_width=3) graph_renderer.node_renderer.data_source.data[ 'hashtag'] = subgraphs.ht.values graph_renderer.node_renderer.data_source.data[ 'frequency'] = subgraphs.frq.values graph_renderer.node_renderer.data_source.data[ 'degree'] = subgraphs.degree.values graph_renderer.node_renderer.data_source.data[ 'subgraph'] = subgraphs.subgraph.values graph_renderer.node_renderer.data_source.data['ix'] = list(subgraphs.index) graph_renderer.node_renderer.data_source.data[ 'subsets'] = subgraphs.subsets.values graph_renderer.inspection_policy = NodesAndLinkedEdges() graph_renderer.selection_policy = NodesAndLinkedEdges() graph_plot.toolbar.active_inspect = [node_hover_tool] graph_plot.renderers.append(graph_renderer) #output_file(path+topic+"_graph_N"+str(nodeThresh)+'E'+str(edgeThresh)+".html") show(graph_plot) subgraphs = subgraphs.sort_values(by='subgraph') return subgraphs
def make_plottable(colors=None, sizes=None, tweets=None): global NETWORK if not NETWORK: NETWORK = reload_json(USER_GRAPH_FNAME, nx.DiGraph, transform=nx.node_link_graph) graph = from_networkx(NETWORK, graphviz_layout, prog="sfdp") if not colors: node_color = Spectral4[0] else: node_color = "color" graph.node_renderer.data_source.add(colors, "color") if not sizes: node_size = 8 else: node_size = "size" graph.node_renderer.data_source.add(sizes, "size") if tweets: graph.node_renderer.data_source.add(tweets, "desc") edge_width = 0.3 select_edge_width = 2 node_alpha = 0.95 edge_alpha = 0.3 edge_color = "#666666" select_color = Spectral4[2] hover_color = Spectral4[1] graph.node_renderer.glyph = Circle( size=node_size, fill_color=node_color, fill_alpha=node_alpha, line_color=node_color, line_alpha=node_alpha, ) graph.node_renderer.selection_glyph = Circle(size=node_size, fill_color=select_color, line_color=select_color) graph.node_renderer.hover_glyph = Circle(size=node_size, fill_color=hover_color, line_color=hover_color) graph.edge_renderer.glyph = MultiLine(line_color=edge_color, line_alpha=edge_alpha, line_width=edge_width) graph.edge_renderer.selection_glyph = MultiLine( line_color=select_color, line_width=select_edge_width) graph.edge_renderer.hover_glyph = MultiLine(line_color=hover_color, line_width=select_edge_width) graph.selection_policy = NodesAndLinkedEdges() graph.inspection_policy = NodesAndLinkedEdges() return graph
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
def NLD_random_processing_graph(g, weights, colors, layout): degree_sequence = sorted([d for n, d in g.degree()], reverse=True) magicnumber = (g.number_of_nodes() / degree_sequence[0]**2) r = 2.2 / magicnumber my_points = nx.random_layout(g) graph = from_networkx(g, layout) my_colors = [] for key, value in my_points.items(): x = value[0] + 1.0 # x = -1 .. +1, so move to 0 ... 2 y = value[1] + 1.0 # y = -1 .. +1, so move to 0 ... 2 my_colors.append("#%02x%02x%02x" % (int(50 + 100 * x), int(30 + 100 * y), 150)) # nodes and egdes attributes graph.node_renderer.data_source.data['degree'] = list(zip(*g.degree))[1] graph.node_renderer.data_source.data['degree2'] = [ sqrt(x + 6) for x in graph.node_renderer.data_source.data['degree'] ] graph.node_renderer.data_source.data['nodessize'] = [ x * 115 / (sqrt(g.number_of_nodes() + (np.mean(degree_sequence)))) for x in graph.node_renderer.data_source.data['degree2'] ] graph.node_renderer.data_source.data['my_fill_color'] = my_colors 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.85, fill_color='my_fill_color') 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=3, line_alpha=0.8, line_color='color') graph.edge_renderer.selection_glyph = MultiLine(line_width=4, line_alpha=0.8, line_color='red') graph.edge_renderer.hover_glyph = MultiLine(line_width=4, 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
def plot_bokeh_network_i(G, id, layout=nx.circular_layout, output="testing.html"): 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(), WheelZoomTool()) graph_renderer = from_networkx(G, 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() x, y = zip(*graph_renderer.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(graph_renderer) output_file(output) save(plot)
def create_figure(G, ntx): 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 = "BTC Block Visualization" citation = Label(x=0, y=-20, x_units='screen', y_units='screen', text='This block contains '+str(ntx)+\ ' transactions between '+str(len(G.nodes()))+\ ' addresses. The most active address transacted with '+str(max(list(dict(G.degree()).values())))+\ ' addresses.', render_mode='css', border_line_color='red', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) #citation = Label(x=40, y=0, x_units='screen', y_units='screen', # text='There were '+str(ntx)+' transactions total. The most active transactor was involved in '+str(max(list(dict(G.degree()).values())))+' transactions.', # render_mode='css', # border_line_color='black', border_line_alpha=1.0, # background_fill_color='white', background_fill_alpha=1.0) plot.add_layout(citation) plot.add_tools(HoverTool(tooltips=None), TapTool(), BoxSelectTool(), WheelZoomTool(), PanTool()) graph_renderer = from_networkx(G, nx.circular_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 visual(): ''' visualze whole graph ''' nx = networkx.Graph() color_movie = Spectral4[0] color_actor = Spectral4[3] for aid in g.all_actors: inf = g.all_actors[aid]['age'] nx.add_node(aid, type = 'Actor', item_name = aid, info = "Age: " + str(inf), color = color_actor, size = 10) for mid in g.all_movies: # if g.all_movies[mid]['actors'] == []: # continue inf = g.all_movies[mid]['box_office'] nx.add_node(mid, type = 'Movie', item_name = mid,info = "Box Office: " + str(inf), color = color_movie, size = 15) for mid in g.all_movies: movie = g.all_movies[mid] for aid in movie['actors']: if aid not in g.all_actors: continue nx.add_edge(mid, aid) for aid in g.all_actors: for mid in g.all_actors[aid]['movies']: if mid not in g.all_movies: continue nx.add_edge(aid, mid) p = Plot(plot_width=1200, plot_height=1200, x_range=Range1d(-3, 3), y_range=Range1d(-3, 3)) p.title.text = "Visualization of the graph" p.add_tools(HoverTool(tooltips=[("Name", "@item_name"), ("Info", "@info")]), TapTool(), BoxSelectTool()) graph_renderer = from_networkx(nx, networkx.spring_layout, scale=7, center=(0, 0)) graph_renderer.node_renderer.glyph = Circle(size='size', fill_color='color') graph_renderer.node_renderer.selection_glyph = Circle(size='size', fill_color=Spectral4[2]) graph_renderer.node_renderer.hover_glyph = Circle(size='size', fill_color=Spectral4[1]) graph_renderer.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=1) graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color='#440154', line_width=1) graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=1) graph_renderer.selection_policy = NodesAndLinkedEdges() graph_renderer.inspection_policy = NodesOnly() p.renderers.append(graph_renderer) script, div = components(p) return render_template("visualization.html", script=script, div=div)
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 get_bokeh_plot(self): """Get a nice Bokeh plot of the network.""" 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 = "Agents network" plot.add_tools( HoverTool(tooltips=[("AgentID", "@index")]), TapTool(), ) graph_renderer = from_networkx( self.graph, nx.spring_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=3, ) graph_renderer.edge_renderer.selection_glyph = MultiLine( line_color=Spectral4[2], line_width=3, ) graph_renderer.selection_policy = NodesAndLinkedEdges() graph_renderer.inspection_policy = NodesOnly() plot.renderers.append(graph_renderer) return plot
def network_total_following(self, user_dict, n_neighbors=5): graph = nx.Graph() self.add_nodes(graph, user_dict) self.add_edges(graph, user_dict) for node in list(graph.nodes()): if len(list(graph.neighbors(node))) < n_neighbors: graph.remove_node(node) plot = Plot( plot_width=1140, plot_height=720, x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1)) plot.add_tools( HoverTool(tooltips=[('User','@name'), ('Neighbors', '@neighbors')], line_policy='nearest'), TapTool(), BoxSelectTool(), PanTool(), WheelZoomTool(), ResetTool()) graph_render = from_networkx(graph, nx.spring_layout, scale=2.5, center=(0,0)) graph_render.node_renderer.data_source.data['name'] = list(graph.nodes()) list_edges = self.get_list_of_edges(graph) graph_render.node_renderer.data_source.data['neighbors'] = list_edges mapper = linear_cmap('neighbors', palette=Plasma11, low=min(list_edges), high=max(list_edges)) graph_render.node_renderer.glyph = Circle( size=10, fill_color=mapper) graph_render.node_renderer.hover_glyph = Circle( size=200, fill_color=mapper) graph_render.node_renderer.selection_glyph = Circle( size=200, fill_color=mapper) graph_render.edge_renderer.glyph = MultiLine( line_color=Greys4[2], line_alpha=0.3, line_width=1) graph_render.edge_renderer.hover_glyph = MultiLine( line_color=Greys4[1], line_width=2) graph_render.edge_renderer.selection_glyph = MultiLine( line_color=Greys4[0], line_width=3) graph_render.selection_policy = NodesAndLinkedEdges() graph_render.inspection_policy = NodesAndLinkedEdges() plot.renderers.append(graph_render) show(plot)
def plot_create(self, doc): plot = figure(title="Belief Graph") plot.axis.visible = False node_labels = nx.get_node_attributes(self.bel_graph, 'id') node_labels = tuple([label for label in node_labels.values()]) ncolor = ['#2b83ba' for name in node_labels] nsize = [15 for name in node_labels] graph = from_networkx(self.bel_graph, nx.spring_layout, scale=1, center=(0, 0)) graph.node_renderer.glyph = Circle(size='nsize', fill_color='ncolor') graph.node_renderer.selection_glyph = Circle(size='nsize', fill_color='#054872') graph.node_renderer.hover_glyph = Circle(size='nsize', fill_color='#abdda4') graph.name = "bel_graph" graph.node_renderer.data_source.data.update( dict(id=node_labels, ncolor=ncolor, nsize=nsize)) graph.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=5) graph.edge_renderer.selection_glyph = MultiLine(line_color='#054872', line_width=5) graph.edge_renderer.hover_glyph = MultiLine(line_color='#abdda4', line_width=5) graph.selection_policy = NodesAndLinkedEdges() # graph.inspection_policy = EdgesAndLinkedNodes() plot.renderers.append(graph) x, y = zip(*graph.layout_provider.graph_layout.values()) source_graph = ColumnDataSource(data=dict(x=x, y=y, id=node_labels)) labels = LabelSet(x='x', y='y', text='id', source=source_graph) plot.renderers.append(labels) # add tools to the plot plot.add_tools(HoverTool(names=["bel_graph"]), TapTool()) doc.add_root(plot)
def plotGraph(graph, title=None, graphSavePath=None, networkPath=None): for k, adjacencies in zip(list(graph.nodes.keys()), graph.adjacency()): graph.nodes[k]["degree"] = len(adjacencies[1]) if networkPath is not None: for city in graph.nodes(): graph.nodes[city]["code"] = graph.networkPath.stationList.getCode( city) plot_height = 700 plot = Plot(plot_width=900, plot_height=plot_height, x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1)) plot.title.text = title node_hover_tool = HoverTool( tooltips=[("Miasto", "@index"), ("Kod miasta", "@code"), ("Stopien wierzcholka", "@degree")]) plot.add_tools(WheelZoomTool(), PanTool(), SaveTool(), node_hover_tool, BoxZoomTool(), ResetTool()) # , TapTool()) graph_renderer = from_networkx(graph, nx.spring_layout, scale=1, center=(0, 0)) graph_renderer.node_renderer.glyph = Circle(size=12, fill_color="yellow") graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color="blue") graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color="red") graph_renderer.edge_renderer.glyph = MultiLine(line_color="green", line_alpha=0.3, line_width=1) graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color="blue", line_width=1.2) graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color="red", line_width=1.2) plot.renderers.append(graph_renderer) columnCities = ColumnDataSource(data=dict(city=list(graph.nodes.keys()))) columnsNetwork = [ TableColumn(field="city", title="Miasto"), ] table = DataTable(source=columnCities, columns=columnsNetwork, width=155, height=plot_height) layout = row(plot, table) if graphSavePath is not None: output_file(graphSavePath, title) show(layout)
def modify_doc(doc): plot = Plot(height=400, width=400, x_range=Range1d(0, 3), y_range=Range1d(0, 3), min_border=0) renderer = plot.add_glyph(source, MultiLine(xs='xs', ys='ys')) tool = PolyEditTool(renderers=[renderer]) psource = ColumnDataSource(dict(x=[], y=[])) prenderer = plot.add_glyph(psource, Circle(x='x', y='y', size=10)) tool.vertex_renderer = prenderer plot.add_tools(tool) plot.toolbar.active_multi = tool plot.toolbar_sticky = False div = Div(text='False') def cb(attr, old, new): try: if cds_data_almost_equal(new, expected): div.text = 'True' except ValueError: return source.on_change('data', cb) code = RECORD("matches", "div.text") plot.add_tools( CustomAction(callback=CustomJS(args=dict(div=div), code=code))) doc.add_root(column(plot, div))
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 != []
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 plotNetXBokeh(src_abv,src_belw,q_csid): max_XNodeVal = max(src_belw['xs_node']) max_YNodeVal = max(src_belw['ys_node']) buffer = 0.1 plot = figure(sizing_mode='scale_width',x_range=(-max_XNodeVal-buffer, max_XNodeVal+buffer),y_range=(-max_YNodeVal-buffer, max_YNodeVal+buffer)) plot.outline_line_color = None source_belw = ColumnDataSource(src_belw) source_abv = ColumnDataSource(src_abv) glyph = MultiLine(xs="xs_line", ys="ys_line", line_color='lcolour', line_width='weight',line_alpha='alpha') plot.add_glyph(source_belw, glyph) plot.add_glyph(source_abv, glyph) #add the above threshold lines last so it overlays the below lines plot.circle('xs_node', 'ys_node', source=source_belw, size='size', color='colour',line_color='#020c15',line_width=0.5,name='showhover') plot.circle('xs_node', 'ys_node', source=source_abv, size='size', color='colour',line_color='#020c15',line_width=0.5,name='showhover') dictHoverLabels = {'CSID':'csid','Name':'cname','EucliDist':'euclidist'} node_hover_tool = customHoverTool(dictHoverLabels,400) # node_hover_tool = hover = HoverTool(names=['showhover'], tooltips=""" # <div style="word-wrap: break-word; width: 400px;"> # <p><span style="font-size: 5; font-weight: bold;">CSID: @csid</span><p> # <p><span style="font-size: 5; font-weight: bold;">Name: @cname</span><p> # <p><span style="font-size: 5; font-weight: bold;">EucliDist: @euclidist</span><p> # </div> # """) plot.add_tools(node_hover_tool) plot.toolbar.logo = None plot.min_border = 0 plot.axis.visible = False plot.toolbar.autohide = True plot.grid.visible = False return plot