def pyvis(height): # Load Pyvis network got_net = Network(height="750px", width="100%", bgcolor="#222222", font_color="white") got_net.barnes_hut() got_data = pd.read_csv( "https://www.macalester.edu/~abeverid/data/stormofswords.csv") sources = got_data['Source'] targets = got_data['Target'] weights = got_data['Weight'] edge_data = zip(sources, targets, weights) for e in edge_data: src = e[0] dst = e[1] w = e[2] got_net.add_node(src, src, title=src) got_net.add_node(dst, dst, title=dst) got_net.add_edge(src, dst, value=w) neighbor_map = got_net.get_adj_list() for node in got_net.nodes: node["title"] += " Neighbors:<br>" + "<br>".join( neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]]) got_net.write_html("gameofthrones.html") return got_net.html, height, "Pyvis Network"
def evaluate_match_based(video_space, estimator, plot=True, thr=0.4): estimator.fit(video_space) distances, indexes = estimator.kneighbors(video_space, n_neighbors=20) if plot == True: plt.hist(distances[:, 1::].ravel(), bins=100) results, results_distances = filter_results(distances, indexes, thr) net = Network(notebook=True, height='1000px', width='1000px') net.barnes_hut() for i, l in enumerate(labels): net.add_node(str(i), label=str(l)) for i, d in enumerate(results): for j, m in enumerate(d): if j != 0: net.add_edge(str(i), str(m), weight=str(results_distances[i][j])) net.show_buttons(filter_=['physics']) net.show('mygraph.html') return net
def create_viz_html(graph, filename): filename = ensure_html_filename(filename) g_vis = Network() g_vis.barnes_hut() g_vis.from_nx(graph) g_vis.show(filename)
def construct_network(df): g = Network("800px", "100%", bgcolor="#3c4647", font_color="white") for artist in df.artist: g.add_node(artist, label=artist, color="#26d18f") for related in df.related: g.add_node(related, label=related, color="#8965c7") g.add_edges(list(zip(df.artist, df.related))) counts = df.related.value_counts() for node in g.nodes: freq = str(counts.get(node['id'], 1)) # nodes with a value will scale their size # nodes with a title will include a hover tooltip on the node node.update({"value": freq, "title": f"Frequency: {freq}"}) g.inherit_edge_colors("to") for e in g.edges: edge_label = f'{e["from"]} ---> {e["to"]}' e.update({"title": edge_label}) g.barnes_hut(gravity=-17950, central_gravity=4.1, spring_length=220, spring_strength=.140, damping=.66, overlap=1) g.show("spotify_example.html")
def network_visualization(path='./socnetvis.html', alphabet=False): weights = {'best': 4, 'good': 2, 'friend': 1, 'acquaintance': 0.5} net = Network('100%', '100%', bgcolor='#222', font_color='white') net.barnes_hut() for name, node in nodes.items(): for connection_type in node['connections']: for partner in node['connections'][connection_type]: net.add_node(name, name, title=name) net.add_node(partner, partner, title=partner) net.add_edge(name, partner, value=weights[connection_type]) for net_node in net.nodes: node = nodes[net_node['id']] net_node['value'] = len(net.get_adj_list()[net_node['id']]) net_node['title'] += f"<br>{net_node['value']} Connections<br>" if node['notes']: net_node['title'] += f"<i>{node['notes']}</i><br>" for connection_type in node['connections']: if node['connections'][connection_type]: connections = node['connections'][connection_type] net_node['title'] += f"<br>{connection_type.capitalize()} " \ f"({len(connections)})<br>  " net_node['title'] += "<br>  ".join( sorted(connections) if alphabet else connections) + "<br>" if not os.path.isdir(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) net.show(path)
def plotResult(file_in, file_out): got_net = Network(height="100%", width="100%", bgcolor="white", font_color="black") got_net.barnes_hut() got_data = pd.read_csv(file_in) sources = got_data['From'] targets = got_data['To'] weights = got_data['Weight'] x_array = got_data['x'] y_array = got_data['y'] highlight = got_data['Highlight'] edge_data = zip(sources, targets, weights, x_array, y_array, highlight) for e in edge_data: src = e[0] dst = e[1] w = e[2] x_array = e[3] y_array = e[4] h = e[5] v_color_dst = "#ADFF2F" #Green color image_url = 'cat.png' v_shape = 'dot' if (dst in ['central_concentrator'] or h == 1): image_url = 'cat.png' v_shape = 'circle' got_net.add_node(src, shape=v_shape, title=src, x=x_array, y=y_array, color="#ADFF2F") #Green color got_net.add_node(dst, shape=v_shape, title=dst, x=x_array, y=y_array, color=v_color_dst) got_net.add_edge(src, dst, value=h) neighbor_map = got_net.get_adj_list() # add neighbor data to node hover data for node in got_net.nodes: node["title"] += " Neighbors:<br>" + "<br>".join( neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]]) got_net.set_options( 'var options = { "edges": { "arrows": { "middle": { "enabled": true } }, "color": { "inherit": "false"}, "smooth": false},"physics": {"enabled": true, "forceAtlas2Based":{ "gravitationalConstant": -500, "springLength": 100, "avoidOverlap": 1}, "minVelocity": 0.75, "solver": "forceAtlas2Based"}}' ) got_net.show(file_out)
def build_pyvis(filename): header = metadata_header(filename) net = Network("95%", "100%", heading=header) net.show_buttons() nodes, edges = triplet(filename) node_weight = count_node_weight(edges) for node in nodes: group = node["labels"] if node["labels"] else "" net.add_node( node["alias"], label=node["name"], group=group, size=((sqrt(node_weight[node["alias"]]) + 1) * 5), ) for edge in edges: net.add_node(edge["subject"], color="blue") net.add_node(edge["object"], color="blue") net.add_edge(edge["subject"], edge["object"], title=edge["predicate"]) net.barnes_hut( gravity=-4000, central_gravity=0.3, spring_strength=0.001, damping=0.09, overlap=1, ) net.show("index.html")
def drawRscRscGraph_advanced(self, RscRscMatrix, weight_threshold, directed, encryption): rows, cols = np.where(RscRscMatrix > weight_threshold) weights = list(); for x in range(len(rows)): weights.append(RscRscMatrix[rows[x]][cols[x]]) #got_net = Network(height="750px", width="100%", bgcolor="white", font_color="#3de975", directed=directed) got_net = Network(height="750px", width="100%", bgcolor="white", font_color="black", directed=directed) ##f57b2b # set the physics layout of the network got_net.barnes_hut() edge_data = zip(rows, cols, weights) for e in edge_data: src = self.resourceList[e[0]] # convert ids to labels dst = self.resourceList[e[1]] w = e[2] if(encryption): src = Utilities.AES_ECB_Encrypt(self,src.encode('utf-8')) dst = Utilities.AES_ECB_Encrypt(self,dst.encode('utf-8')) # I have to add some options here, there is no parameter highlight = {'border': "#3de975", 'background': "#41e9df"} #color = {'border': "#000000", 'background': "#123456"} got_net.add_node(src, src, title=src, labelHighlightBold=True, color={'highlight': highlight}) got_net.add_node(dst, dst, title=dst , labelHighlightBold=True, color={'highlight': highlight}) got_net.add_edge(src, dst, value=w, title=w) neighbor_map = got_net.get_adj_list() dict = got_net.get_edges() self.getResourceList() # add neighbor data to node hover data for node in got_net.nodes: counter = 0 if(directed): node["title"] = "<h3>" + node["title"] + " Output Links: </h3>" else: node["title"] = "<h3>" + node["title"] + " Links: </h3>" for neighbor in neighbor_map[node["id"]]: if(counter % 10 == 0): node["title"] += "<br>::: " + neighbor else: node["title"] += " ::: " + neighbor node["value"] = len(neighbor_map[node["id"]]) counter += 1 got_net.show_buttons(filter_=['nodes', 'edges', 'physics']) got_net.show_buttons(filter_=['physics']) got_net.show("PMSocial.html")
def drawActivityResourceGraph_advanced(self, ActivityRscMatrix, weight_threshold, directed, splitted): rows, cols = np.where(ActivityRscMatrix > weight_threshold) weights = list(); for x in range(len(rows)): weights.append(ActivityRscMatrix[rows[x]][cols[x]]) got_net = Network(height="750px", width="100%", bgcolor="black", font_color="#f57b2b", directed= directed) # set the physics layout of the network got_net.barnes_hut() edge_data = zip(rows, cols, weights) counter = 1 for e in edge_data: src = self.activityList[e[0]] # convert ids to labels dst = self.resourceList[e[1]] w = e[2] # I have to add some options here, there is no parameter highlight = {'border': "#3de975", 'background': "#41e9df"} if(splitted): got_net.add_node(src, src, title=src, labelHighlightBold=True, color={'highlight': highlight},shape='square') got_net.add_node(dst+ "__" +str(counter) , dst , title=dst , labelHighlightBold=True, color={'border': "#dd4b39", 'background': "#dd4b39", 'highlight': highlight}) got_net.add_edge(src, dst+ "__" +str(counter), value=w, title=w) counter +=1 else: got_net.add_node(src, src, title=src, labelHighlightBold=True, color={'highlight': highlight},shape='square') got_net.add_node(dst , dst, title=dst , labelHighlightBold=True, color={'border': "#dd4b39", 'background': "#dd4b39", 'highlight': highlight}) got_net.add_edge(src, dst , value=w, title=w) neighbor_map = got_net.get_adj_list() dict = got_net.get_edges() self.getResourceList() # add neighbor data to node hover data for node in got_net.nodes: counter = 0 if(directed): node["title"] = "<h3>" + node["title"] + " Output Links: </h3>" else: node["title"] = "<h3>" + node["title"] + " Links: </h3>" for neighbor in neighbor_map[node["id"]]: if(counter % 10 == 0): node["title"] += "<br>::: " + neighbor else: node["title"] += " ::: " + neighbor node["value"] = len(neighbor_map[node["id"]]) counter += 1 got_net.show_buttons(filter_=['nodes', 'edges', 'physics']) got_net.show_buttons(filter_=['physics']) got_net.show("PMSocial.html")
def interactiveGraphExtended(G): # plot interactive graph using pyvis, with degree, no of node labeled, size depends on nodes' degree nt = Network(height="750px", width="100%", bgcolor="#222222", font_color="white") nt.barnes_hut(spring_strength=0.006) for node in G: nt.add_node(node, label=G.degree(node), title="I am node "+str(node), value=G.degree(node)) for edge in G.edges: nt.add_edge(int(edge[0]), int(edge[1]), color='white') nt.show("nx.html")
def corr_graph(Source=list(windows_df_filtered_tb.Table.unique()), Destination=list(windows_df_filtered_tb.Table.unique())): sp_graph, sp_list, sp_colors, sp_sizes = shortest_path(windows_df_filtered_tb,Source,Destination) # Check if the sp_list returned is not NULL which means there is no path and if sp_list == 1 this means that the Table name in Source and Destination is the same if sp_list is not None and len(sp_list) > 1: sp_gr=Network(notebook=True, bgcolor="#222222", font_color="white") sp_gr.add_nodes(sp_list, value=sp_sizes, title=sp_list, color=sp_colors) sp_gr.barnes_hut() sp_gr.from_nx(sp_graph) return(sp_gr.show("graphs/shortest_path_graph.html"))
def interactive(file_in, form): i = Network(height=1080, width=1920) #can specify your screen resolution i.toggle_hide_edges_on_drag(False) i.barnes_hut() form = str(sys.argv[1]) if sys.argv[1] == '-edgelist': i.from_nx(nx.read_weighted_edgelist(file_in)) i.show("./temp/" + str(sys.argv[2]) + ".html") elif sys.argv[1] == '-graphml': i.from_nx(nx.read_graphml(file_in)) i.show(str(sys.argv[2]) + ".html")
def main(): net = Network(height=600, width=900) net.barnes_hut() dbName = "pcapDb" if (not os.path.exists(dbName)): conn = sqlite3.connect(dbName) conn.execute( """create table packetdata (src text,dst text,len integer);""") else: conn = sqlite3.connect(dbName) cursor = conn.cursor() header_struct = struct.Struct('!I') sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("localhost", 9888)) sock.listen(1) q = queue.Queue() reciever, _ = sock.accept() t = threading.Thread(target=display, args=(q, net)) # t.start() while (True): data_len = recvall(reciever, header_struct.size) (data_len, ) = header_struct.unpack(data_len) data = recvall(reciever, data_len) data = pickle.loads(data) # print(data) nodes = set() for i in data: if (i is None): continue src, dst, length = i # print(type(i)) cursor.execute( "insert into packetdata (src,dst,len) values(?,?,?)", (src, dst, length)) nodes.add(src) nodes.add(dst) weights = [] # print("Here") for i in nodes: la = "IP: " + i net.add_node(i, label=i, title=la) for i in data: if (i is None): continue src, dst, weight = i net.add_edge(src, dst, value=weight) net.write_html("index.html") time.sleep(4)
def new_draw(self): """ draw the ARN using the class attributes Args: nothing Returns: a local generated web page """ got_net = Network(height="750px", width="100%", bgcolor="#222222", font_color="white") got_net.heading = "Nucleotids" # set the physics layout of the network got_net.barnes_hut() cp = 0 for nuk in self.list_nucleotide: for tuples in nuk.tup: if tuples.relation in self.grps.keys(): relation_type = self.grps.get(tuples.relation) else: relation_type = 0 relation_type = str(nuk.paired_type) got_net.add_node(tuples.tup[0], label="(" + str(tuples.tup[0]) + ")" + " -> " + str(tuples.tup[1]) + " : " + str(relation_type), group=relation_type) got_net.add_node(tuples.tup[1], label="(" + str(tuples.tup[1]) + ")" + " -> " + str(tuples.tup[0]) + " : " + str(relation_type), group=relation_type) got_net.add_edge(tuples.tup[0], tuples.tup[1]) cp += 1 # got_net.add_node(src, src, title=src) # got_net.add_node(dst, dst, title=dst) # got_net.add_edge(src, dst, value=w) # neighbor_map = got_net.get_adj_list() # add neighbor data to node hover data '''for node in got_net.nodes: node["title"] += " Neighbors:<br>" + \ "<br>".join(neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]])''' got_net.show("networkRNA.html")
def vis_graph(): """ using pyvis """ # https://pyvis.readthedocs.io/en/latest/tutorial.html#example-visualizing-a-game-of-thrones-character-network nt = Network(height="750px", width="100%", bgcolor="#222222", font_color="white") nt.barnes_hut() nt.from_nx(G) neighbor_map = nt.get_adj_list() for node in nt.nodes: node["title"] += " neighbors:<br>" + "<br>".join(neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]]) nt.show("rappers.html")
def make_graph(self, inp): nx_graph = nx.MultiDiGraph() nodes = [] inp = ast.literal_eval(str(inp)) inp.sort(key=lambda x: x['value'], reverse=True) for x in inp: print(x) if x["_from"] not in nodes: nodes.append(x["_from"]) nx_graph.add_node(x["_from"], title=x['_from'], color="#557BEA") if x["_to"] not in nodes: nodes.append(x["_to"]) nx_graph.add_node(x["_to"], title=x["_to"], color="#557BEA") if (float(x["value"]) == 1): nx_graph.add_edge(x["_to"], x["_from"], label=round(x["value"], 5), size=120, arrowStrikethrough=True, width=x["value"] * 10, color="#BB62FF") else: if not (nx_graph.has_edge(x["_from"], x["_to"], key=None) or nx_graph.has_edge(x["_to"], x["_from"], key=None)): nx_graph.add_edge(x["_from"], x["_to"], label=round(x["value"], 5), arrowStrikethrough=False, width=x["value"] * 10, color="#4FCFFF") nx_graph.add_edge(x["_to"], x["_from"], arrowStrikethrough=False, width=x["value"] * 10, color="#4FCFFF") g = Network(height=950, width=1730, notebook=True, directed=True, bgcolor='#171a23', font_color='white') g.toggle_hide_edges_on_drag(True) g.get_network_data() g.barnes_hut() g.from_nx(nx_graph, default_edge_weight=True, default_node_size=70) g.show("test.html") self.get_html(0)
def plot_graph(df_path, graph_name=None, graph_options="graph_options.data"): df = pd.read_csv(df_path) if graph_name is None: graph_name = df_path[:df_path.find(".csv")] + "_graph" with open(graph_options, 'rb') as f: graph_options = pickle.load(f) graph = Network(height="100%", width="100%", bgcolor="#222222", font_color="white") graph.barnes_hut() create_graph(graph, df) graph.set_options(graph_options) graph.show(graph_name + ".html")
def pyvisdraw(g, title='', **kwargs): ''' use pyvis to draw graph ''' net = Network(height='100%', width='100%', bgcolor='#222222', font_color='white', **kwargs) # net = Network(**kwargs) net.barnes_hut() net.from_nx(make_nx(g)) # net.show_buttons(filter_=['physics']) # net.toggle_physics(1) Path('~/libcolgraph').expanduser().mkdir(parents=True, exist_ok=True) path = Path('~/libcolgraph/{}_{}.html'.format(title, len(g))).expanduser() net.show(str(path))
def visualize(graph_nx, name='graph'): got_net = Network(height="750px", width="100%", bgcolor="#222222", font_color="white") # set the physics layout of the network got_net.barnes_hut() got_net.from_nx(graph_nx) # add neighbor data to node hover data neighbor_map = got_net.get_adj_list() for node in got_net.nodes: node["title"] += " Neighbors:<br>" + "<br>".join(neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]]) got_net.show_buttons() got_net.show(f'{name}.html')
def pyvisdraw(g, title='', **kwargs): ''' use pyvis to draw graph ''' net = Network(height='100%', width='100%', bgcolor='#222222', font_color='white', **kwargs) # net = Network(**kwargs) net.barnes_hut() net.from_nx(make_nx(g)) # net.show_buttons(filter_=['physics']) # net.toggle_physics(1) net.show("viz/{}_{}.html".format(title, len(g)))
def plot_graph(graph, background_color='white', font_color='grey', with_edge_label=True, central_gravity=2.0, solver='', height='750px', width='100%', filter_=['']): ''' Creates a pyvis interactive Network Graph from a NetworkX graph object. ''' G = Network(notebook=True, height=height, width=width, bgcolor=background_color, font_color=font_color) color = { 0: '#fb217f', 1: '#fb217f', 2: '#88b1fb', 3: '#88b1fb', 4: '#88b1fb' } deg = dict(graph.in_degree()) for node in graph: md = max(deg.values()) color_id = min(deg[node], 4) G.add_node(node, title=node, label=node, size=(md - deg[node] + 1) * 4, color=color[color_id]) for edge in graph.edges(): if with_edge_label: label = graph.get_edge_data(edge[0], edge[1])['relation'] else: label = '' G.add_edge(edge[0], edge[1], label=label) if solver == 'barnes_hut': G.barnes_hut(central_gravity=central_gravity) else: G.force_atlas_2based(central_gravity=central_gravity) G.show_buttons(filter_=filter_) return G
def create_net_viz(self): net_viz = Network(height=self.height, width=self.width, bgcolor=self.bg_color, font_color=self.font_color) net_viz.barnes_hut() for _, values in self.data.iterrows(): source = str(self.nodes_titles_dict.get(values[self.source_col])) source_image_path = ImageHandler(values[self.source_col], 'png', 'circled', self._config).image_path target = str(self.nodes_titles_dict.get(values[self.target_col])) target_image_path = ImageHandler(values[self.target_col], 'png', 'circled', self._config).image_path source_node_color = self._get_node_color(values[self.source_col]) target_node_color = self._get_node_color(values[self.target_col]) edge_color = get_edge_color(source_node_color, target_node_color) edge_title = values[self.edge_title_col] edge_sub_title = values[self.edge_sub_title_col] weight = 4 net_viz.add_node(source, label=source, title=get_node_popup_template(source), color=source_node_color, shape='image', image=source_image_path) net_viz.add_node(target, label=target, title=get_node_popup_template(target), color=target_node_color, shape='image', image=target_image_path) edge_audio_html_tag = self._get_edge_audio_html_tag( edge_title, edge_sub_title) net_viz.add_edge(source, target, title=get_edge_popup_template( edge_title, edge_sub_title, edge_audio_html_tag), value=weight, color=edge_color) add_node_values(net_viz) self.net_viz = net_viz
def networkx_graph_to_pyvis_network( g: nx.Graph, node_label: str = 'label', node_title: str = 'title', node_size: str = 'size', node_color: str = 'color', edge_weight: str = 'weight', height: str = '650px', width: str = '100%', notebook: bool = False, heading: str = '', gravity: int = -1000, ) -> Network: node_labels = nx.get_node_attributes(g, node_label) node_titles = nx.get_node_attributes(g, node_title) node_sizes = nx.get_node_attributes(g, node_size) node_colors = nx.get_node_attributes(g, node_color) edge_widths = nx.get_edge_attributes(g, edge_weight) network = Network(height=height, width=width, directed=nx.is_directed(g), notebook=notebook, heading=heading) for node in g.nodes: label = node_labels.get(node, node) title = node_titles.get(node, node) size = node_sizes.get(node, 10) color = node_colors.get(node, COLORS[0]) network.add_node(node, label=label, title=title, size=float(size), color=color) for edge in g.edges: width = edge_widths.get(edge, 1) network.add_edge(*edge, width=float(width)) network.barnes_hut(gravity=gravity) return network
def sequence_sample(self, sess, chars, vocab): with open('data/review_example_sequence.txt') as f: data = f.read() state = sess.run(self.cell.zero_state(1, tf.float32)) x = np.zeros((1, 1)) for activity in data.split("->"): x[0, 0] = vocab[activity] feed = {self.input_data: x, self.initial_state: state} [probs, state] = sess.run([self.probs, self.final_state], feed) ps = probs[0] if activity == "time-out 2": G = Network(height=1000, width=1000, directed=True) G.add_node(activity, level=0) index = 0 for p in ps: if p > 0.01: if chars[index] == "\n": index += 1 continue print(activity + "\t\t" + chars[index] + "\t{%f}" % p) G.add_node(chars[index], physics=True, level=1) G.add_edge(activity, chars[index], value=int(p * 100), title=int(p * 100), physics=True, arrowStrikethrough=False) index += 1 print() G.barnes_hut(gravity=-10000) # G.show_buttons() G.save_graph( os.path.join( "results", re.sub('[-=.#/?:$}]', '', activity) + "_sequence.html"))
def see_graph(self, htmlname='MetabolicNetwork.html', height="1080px", width="1080px", colorHighNodes=5): ''' #***DEPRECATED METHOD***# #***use see_graph2***# Provides a visual representation of the network using pyvis Metabolites are represented by yellow dots Reationss are represented by green triangles Metabolite Highlights are represented by red dots and denote highest in_degrees metabolites if nodes are not metabolites or reaction default blue dot is used :param htmlname:(str) name of exit file :param height:(num) height of html window display :param width:(num) width of html window display :param colorHighNodes:(int) number of nodes to color highlight, if 0 will not highlight any node :return: creates html file and opens it on default browser ''' nt = Network(height, width) nt.from_nx(self.mnetwork) for dit in nt.nodes: if str(dit['title']).startswith('R'): dit['shape'] = 'triangle' dit['color'] = 'green' if str(dit['title']).startswith('M'): dit['color'] = 'rgb(255, 211, 0)' nt.show_buttons(filter_=['physics', 'edges']) nt.inherit_edge_colors_from(False) if colorHighNodes > 0: mustcolor = self.biggestM_indegrees(colorHighNodes) for dit2 in nt.nodes: if str(dit2['title']) in mustcolor: dit2['color'] = 'red' nt.barnes_hut(gravity=-3000) nt.toggle_stabilization(True) nt.show(htmlname)
def make_graph(self): graph_data = [] for key in self.ner_dct.keys(): lst = self.ner_dct[key] for x in lst: graph_data.append((key, x[0])) poi_net = Network(height="750px", width="100%", bgcolor="#ffffff", font_color="blue") poi_net.barnes_hut() for i in graph_data: src = i[0] dst = i[1] poi_net.add_node(src, label=src, title="src", color="black") poi_net.add_node(dst, label=dst, title="dst", color="#dd4b39") poi_net.add_edge(src, dst) #change this location poi_net.save_graph( "/Users/ankitanand/Box/UB/Fall 2019/IR/Proj1/poi.html")
def show_relations_network_graph(novel_entities: NovelEntities) -> None: print('Displaying relations graph') graph = Network(directed=True, bgcolor="#222222", font_color="white") graph.barnes_hut() graph.set_edge_smooth('dynamic') nodes_dict = {} for named_entity in novel_entities.get_named_entities(): if not any(named_entity.get_kbp_relations()): continue nodes_dict[id(named_entity)] = named_entity value = sum(1 for _ in named_entity.get_as_subject_kbp_relations()) title = named_entity.name if isinstance(named_entity, Character) and named_entity.gender != "UNKNOWN": title += '<br>' + "Gender" + ': ' + named_entity.gender.capitalize( ) for ext_relation in named_entity.get_as_subject_kbp_relations(): relation_desc, _ = __get_relation_name_and_color( ext_relation.relation.relation_str) title += '<br>' + relation_desc.capitalize( ) + ': ' + ext_relation.object_named_entity.name graph.add_node(n_id=id(named_entity), label=named_entity.name, value=value, title=title) for named_entity in novel_entities.get_named_entities(): for ext_relation in named_entity.get_as_subject_kbp_relations(): relation_desc, relation_color = __get_relation_name_and_color( ext_relation.relation.relation_str) # relation_desc += " of" graph.add_edge(id(ext_relation.object_named_entity), id(ext_relation.subject_named_entity), arrowStrikethrough=True, physics=True, title=relation_desc, color=relation_color) graph.show("output/" + novel_entities.name + '.html')
def visualize_random_graph(filename, graph, color_by_degree=True, notebook=False): g = Network(notebook=notebook) g.barnes_hut() G_nodes = graph.nodes # Coloring by degree: if color_by_degree: G_degrees = [graph.degree(node) for node in G_nodes] G_colors = nums_to_greyscale_hex(G_degrees) for node, color in zip(G_nodes, G_colors): g.add_node(node, color=color) # Not coloring by degree: else: for node in G_nodes: g.add_node(node) for edge in graph.edges: g.add_edge(*edge) g.show(filename)
def draw_list(self): """ draw the ARN using the class attributes Args: nothing Returns: a local generated web page """ got_net = Network(height="750px", width="100%", bgcolor="#222222", font_color="white") got_net.heading = "motif detected" # set the physics layout of the network got_net.barnes_hut() cp = 0 for nuk in self.list_motif: for tuples in nuk.tup: if tuples.relation in self.grps.keys(): relation_type = self.grps.get(tuples.relation) else: relation_type = 0 relation_type = str(nuk.paired_type) got_net.add_node(tuples.tup[0], label="(" + str(tuples.tup[0]) + ")" + " -> " + str(tuples.tup[1]) + " : " + str(relation_type), group=relation_type) got_net.add_node(tuples.tup[1], label="(" + str(tuples.tup[1]) + ")" + " -> " + str(tuples.tup[0]) + " : " + str(relation_type), group=relation_type) got_net.add_edge(tuples.tup[0], tuples.tup[1]) cp += 1
def make_graph(subjects: list): # read data df = pd.DataFrame() for subject in subjects: courses = pd.read_json(f"courses/{subject}.json") df = pd.concat([df, courses]) edge_list = make_edge_list(df) node_list, title_list = make_node_list(df) # make graph g = Network(directed=True, height="650px", width="100%", bgcolor="#222222", font_color="white") g.barnes_hut() # spring physics on the edges g.inherit_edge_colors(False) g.add_nodes(node_list, title=title_list) for edge in edge_list: g.add_edge(edge[0], edge[1], color="#94c4fc") # add neighbor data to node hover data for node in g.nodes: prereq = df[df["label"] == node["label"]]["prereq"] prereq = [] if prereq.empty else prereq.item() next_courses = g.neighbors(node["label"]) node["title"] += "<br>Prerequisites:<br>" \ + "<br>".join(prereq) \ + "<br>Next courses:<br>" \ + "<br>".join(next_courses) node["value"] = len(next_courses) + len(prereq) # highlight the node if it serves as a prerequisites for more than 5 course node["font"]["size"] = node["value"] * 5 if node["value"] >= 8: node["color"] = "red" return g