def vis(G): gvis = Network(height='700px', width='700px') gvis.from_nx(G) gvis.toggle_physics(True) gvis.show_buttons() gvis.show("Visualization of INFECTTIOUS daily graph.html")
def filter_network(thresholds, account): filter_ego_attributes(account.connection.attributes) mutual_friends = int(thresholds['mutual_friends']) action = str(thresholds['selected_action']) friendship_duration = int(thresholds['friendship_duration']) total_friends = int(thresholds['total_friends']) age_of_account = int(thresholds['age_of_account']) # Debugging # mutual_friends = 10 # action = "Sharing" # friendship_duration = 365 # total_friends = 355 # age_of_account = 365 set_threshold( Threshold( ConnectionThreshold(mutual_friends, friendship_duration, account.connection.attributes), UserThreshold(total_friends, age_of_account)), account) G = init_graph(account, action, float(thresholds["minimum_trust_value"])) # G = init_graph(account, "Sharing", 0) G2 = Network("500px", "1000px") G2.from_nx(G) G2.show(account.name + ".html") G.clear() plt.close()
def saveGraph(self, target_file): nt = Network(height="700px", width="1000px", heading='Connectivity map', layout=True) nt.from_nx(self.__G) nt.show(target_file)
def show_deck_type_graph(edge_list, h="Headline", edge_limit=8): """ :param edge_limit: :param h: :param edge_list: (node1, node2, edge_weight) :return: None """ import networkx as nx from pyvis.network import Network # type_to_color = {"Aquatic": "blue", "Plant": "green", "Bird": "#ff66ff", "Reptile": "#b366ff", "Beast": "yellow"} G = nx.Graph() # todo use relative frequency G.add_edges_from([(str(e1), str(e2), { "weight": v }) for (e1, e2), v in edge_list.items() if v > edge_limit]) net = Network(notebook=True, width="100%", height="100%", heading=h) net.from_nx(G) net.show(f'{h.replace(",", "-").replace(" ", "")}.html') import webbrowser webbrowser.open(f'{h.replace(",", "-").replace(" ", "")}.html', new=2) time.sleep(3)
def network_pyvis(self, df): G = nx.from_pandas_edgelist(df, edge_attr=True) net = Network(height="500px", width="100%", heading='') sources = df['source'] targets = df['target'] weights = df['weight'] edge_data = zip(sources, targets, weights) for e in edge_data: src = e[0] dst = e[1] w = e[2] net.add_node(src, src, title=src) net.add_node(dst, dst, title=dst) net.add_edge(src, dst, value=w) neighbor_map = net.get_adj_list() net.from_nx(G) net.write_html('tweets/temp.html') return net.html
def create_html(post_id): data = np.load( os.path.join("../dataset/twitter15textgraph", post_id + ".npz")) # Add nodes nx_graph = nx.Graph() for idx, d in enumerate(data['x']): if idx == 0: nx_graph.add_node(idx, label="Source Post", title=d, size=20, color="#023e8a") else: nx_graph.add_node(idx, title=d, size=20, color="#0096c7") # Add edges for n1, n2 in zip(data["edgeindex"][0], data["edgeindex"][1]): nx_graph.add_edge(list(nx_graph.nodes)[n1], list(nx_graph.nodes)[n2], color="#caf0f8") # Output HTML nt = Network("470px", "440px", notebook=True, heading="", bgcolor='#262730', font_color='white') nt.from_nx(nx_graph) nt.show('data.html')
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 vizBN(G): from pyvis.network import Network Gviz = Network(notebook=True, height="500px", width="100%", font_color="white", bgcolor="#222222") Gviz.from_nx(G) Gviz.set_options("""var options = { "physics": { "barnesHut": { "gravitationalConstant": -9950, "centralGravity": 1.15, "springLength": 145, "springConstant": 0.055, "avoidOverlap": 0.2 }, "maxVelocity": 18, "minVelocity": 0.75 }, "nodes": { "color": { "border": "rgba(0,0,0,1)", "background": "rgba(229,218,171,1)", "highlight": { "border": "rgba(229,86,51,1)", "background": "rgba(255,207,70,1)" }, "hover": { "border": "rgba(229,97,106,1)", "background": "rgba(255,206,118,1)" } }, "font": { "face": "verdana" } }, "edges": { "arrows": { "to": { "enabled": true, "scaleFactor": 0.4 }, "from": { "enabled": true, "scaleFactor": 0.4 } }, "color": { "color": "rgba(255,255,255,1)", "highlight": "rgba(255,67,61,1)", "hover": "rgba(255,36,47,1)", "inherit": "both" }, "smooth": false } }""") return Gviz.show("nx.html")
def generateGraph(self) -> Network: G, pos = self.generateNetwork() nt = Network(height='90%', width='100%', heading=f"Dota Peers for {self.player.username}") nt.toggle_physics(False) nt.from_nx(G) return nt
def plt(infile): G = nx.read_gpickle(infile) nt = Network('500px', '500px') nt.from_nx(G) nt.show('nx.html') return
def karate_func(physics): G = nx.karate_club_graph() nt = Network("500px", "500px", notebook=True, heading='Test_3') nt.from_nx(G) # physics=st.sidebar.checkbox('add physics interactivity?') if physics: nt.show_buttons(filter_=['physics']) nt.show('Test_3.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 show_common_eff_graph(): weights = np.empty((len(f), len(f)), dtype=set) for i in range(len(f)): for j in range(len(f)): weights[i, j] = common_words(f.loc[i, "Effect"], f.loc[j, "Effect"]) graph_df = pd.DataFrame(columns=["S", "T", "W", "C", "E1", "E2"]) graph_df.astype({ "S": str, "T": str, "W": int, "C": str, "E1": str, "E2": str }) c = 0 for i in range(len(f)): for j in range(len(f)): if i < j and len(weights[i, j]) > 0: graph_df.loc[c] = [ f.loc[i, "Card name"], f.loc[j, "Card name"], len(weights[i, j]), ", ".join(weights[i, j]), f.loc[i, "Effect"], f.loc[j, "Effect"] ] c += 1 print(graph_df) graph = nx.from_pandas_edgelist(graph_df, source="S", target="T", edge_attr=True) net = Network(notebook=True, width="100%", height="100%") net.from_nx(graph) for node in net.nodes: try: color = type_to_color[f.loc[f["Card name"] == node["label"]] ["Type"][0]] size = (f.loc[f["Card name"] == node["label"]]["Cost"][0] + 1) * 5 shape = part_to_shape[f.loc[f["Card name"] == node["label"]] ["Part"][0]] node.options.update({"color": color, "size": size, "shape": shape}) except KeyError as e: print(node) net.show("example.html") import webbrowser webbrowser.open("example.html", new=2) show(graph_df)
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 visualize(edges, error_codes, resouce_pages, args): G = nx.DiGraph() G.add_edges_from(edges) if args.save_txt is not None or args.save_npz is not None: nodes = list(G.nodes()) adj_matrix = nx.to_numpy_matrix(G, nodelist=nodes, dtype=int) if args.save_npz is not None: base_fname = args.save_npz.replace('.npz', '') scipy.sparse.save_npz(args.save_npz, scipy.sparse.coo_matrix(adj_matrix)) else: base_fname = args.save_txt.replace('.txt', '') np.savetxt(args.save_txt, adj_matrix, fmt='%d') node_info = get_node_info(nodes, error_codes, resource_pages, args) with open(base_fname + '_nodes.txt', 'w') as f: f.write('\n'.join( [nodes[i] + '\t' + node_info[i] for i in range(len(nodes))])) net = Network(width=args.width, height=args.height, directed=True) net.from_nx(G) if args.show_buttons: net.show_buttons() elif args.options is not None: try: with open(args.options, 'r') as f: net.set_options(f.read()) except FileNotFoundError as e: print('Error: options file', args.options, 'not found.') except Exception as e: print('Error applying options:', e) for node in net.nodes: node['size'] = 15 node['label'] = '' if node['id'].startswith(args.site_url): node['color'] = INTERNAL_COLOR if node['id'] in resouce_pages: node['color'] = RESOURCE_COLOR else: node['color'] = EXTERNAL_COLOR if node['id'] in error_codes: node[ 'title'] = f'{error_codes[node["id"]]} Error: <a href="{node["id"]}">{node["id"]}</a>' node['color'] = ERROR_COLOR else: node['title'] = f'<a href="{node["id"]}">{node["id"]}</a>' net.save_graph(args.vis_file)
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 add_graph(dims, file): count = 0 G = nx.Graph() for l in f: words = l.split(', ') G.add_edge(words[0], words[1], weight=1, relation='co-exist') count += 1 nt = Network(str(dims[0]) + 'px', str(dims[1]) + 'px') nt.from_nx(G) nt.repulsion(180, 0.5, 280) nt.show('gtsam.html') return count
def plot_graph(graph): for i in range(len(graph)): graph.nodes[i]["title"] = f"S_{i}" nt = Network("600px", "600px", notebook=True, font_color="grey", heading="Граф") nt.from_nx(graph) # physics = st.checkbox("Добавим немного физики?") # if physics: # nt.show_buttons(filter_=["physics"]) nt.show("Markov_chain.html") HtmlFile = open("Markov_chain.html", "r", encoding="utf-8") source_code = HtmlFile.read() components.html(source_code, height=1200, width=1000)
def build_pyvis_graph(nx_graph, link_title_dict, link_content_dict, node_shape_dict=None): graph = Network(notebook=True, directed=True, width=1000, height=1000) graph.from_nx(nx_graph) for node in graph.nodes: node['label'] = link_title_dict[node['id']] if node['id'] in link_content_dict: node['title'] = link_content_dict[node['id']] if node_shape_dict: node['value'] = node_shape_dict[node['id']] return graph
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 pyVIS(node_list, edge_list): G = nx.Graph() G = nx.from_pandas_edgelist(edge_list, 'Source', 'Target', edge_attr='Weight') nx.set_node_attributes(G, node_list.set_index('ID').to_dict('index')) net = Network(height=1000, width=1000, notebook=True) net.toggle_hide_edges_on_drag = False net.show_buttons( filter_=['physics', 'interaction', 'manuipulation', 'nodes']) net.from_nx(G) net.show("pyvis.html")
def visualize_graph(graph, notebook=False): net = Network(notebook=notebook) net.width = '100%' net.from_nx(graph, edge_weight_transf=float) net.set_options(""" var options = { "nodes": { "font": { "size": 40 } } } """) net.show("word.html")
def show_network(G): nt = Network("700px", "700px", directed=True) nt.from_nx(G) #UNCOMMENT BELOW TO PLAY WITH PHYSICS OF SHOWN GRAPH #nt.show_buttons(filter_=["physics"]) #nt.show_buttons(filter_=['nodes', 'interaction', 'selection']) nt.toggle_physics(status=True) nt.force_atlas_2based(gravity=-500, central_gravity=0.02, damping=0.2, overlap=0.5) nt.show("Most_Related_Artists.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 create_graph(messages: list, people: list, reacts: dict, freq: dict, config: dict): directed = config['graph']['directed'] if directed: reacts_g = nx.DiGraph() else: reacts_g = nx.Graph() reacts_g.add_nodes_from(people) threshold = config['graph']['pair_threshold'] for pair in itertools.combinations(people, 2): make_edge(pair[0], pair[1], reacts, directed, threshold, reacts_g) if directed: make_edge(pair[1], pair[0], reacts, directed, threshold, reacts_g) vis = Network(bgcolor='#222222', font_color="white", height="100%", width="100%", directed=directed) vis.from_nx(reacts_g) neighs = vis.get_adj_list() for edge in vis.edges: edge["value"] = get_pair_reacts(edge["from"], edge["to"], reacts, directed) for node in vis.nodes: neighbors = vis.neighbors(node['id']) n_metadata = [] for neighbor in neighbors: pair = (node['id'], neighbor) matching_edge = [ edge for edge in vis.edges if (edge["from"] in pair and edge["to"] in pair) ][0] n_metadata.append(f'{neighbor} ({matching_edge["value"]})') node['title'] = " Reacts:<br>" + "<br>".join(list(n_metadata)) if config['graph']['adjust_node_size']: node['size'] = config['graph']['base_size'] * log10( (freq[node['id']]) / 10) else: node['size'] = config['graph']['base_size'] return (vis)
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 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 addToGraphSimple(arr): G = nx.DiGraph() for x in range(len(arr)): nd = x G.add_node(nd) # show the MST result for x in range(len(arr)): for y in range(len(arr[x])): if arr[x][y] != 0: G.add_edge(x, y) g = Network(height=800, width=800, notebook=True) g.from_nx(G) return g
def draw_subgraph(G, actor): ''' Input: Main graph G and starting actor Output: Draws subgraph of that actor and their immediate costars Would've been nice to have more than one level deep, but even n=2 for Will Ferrell didn't load ''' print(f'Drawing subgraph for {actor}') nodes = set() nodes.add(actor) for g in G.neighbors(actor): nodes.add(g) subgraph = nx.Graph(G.subgraph(nodes)) net = Network(height="750px", width="100%", bgcolor="#222222", font_color="white") # net.show_buttons(filter_=['nodes']) net.set_options(''' var options = { "physics": { "barnesHut": { "gravitationalConstant": -10450, "centralGravity": 0.8, "springLength": 120, "springConstant": 0.05, "damping": 0.08, "avoidOverlap": 0.56 }, "maxVelocity": 43, "minVelocity": 0.75, "timestep": 0.56 } } ''') net.from_nx(subgraph) # add movie data to hover on edge for node in net.nodes: costar = node['title'] # skip self-references if costar == actor: continue movie_list = G.get_edge_data(actor, costar)['movie_list'] node["title"] += " Movies:<br>" + "<br>".join(movie_list) node["value"] = len(movie_list) file_name = '_'.join(actor.split()) + '.html' net.show(f'{file_name}')
def network_viz(self): # build a networkX graph object from tweet data frame self.net_graph = build_msg_net(self.tdf) # remove self edges self.net_graph.remove_edges_from(self.net_graph.selfloop_edges()) # start pyviz object viz = Network(height=800, width=800) viz.from_nx(self.net_graph) #viz.show_buttons() # open the preset options we want to specifiy viz_options = open("input/pyviz_options.txt", 'r').read() viz.set_options(viz_options) # show the graph in browser viz.show('tweet_network_viz.html') import pdb pdb.set_trace()