def interactive_graph(graph, prd_mode=False): # Create the Pyvis network object if prd_mode: sna_visualisation = net.Network(height="100%", width="100%") else: sna_visualisation = net.Network(height="100%", width="65%") # Add each node to the Pyvis object along with it's attributes for nodes, attributes in graph.nodes(data=True): sna_visualisation.add_node(nodes, **attributes) # for each edge and its attributes in the networkx graph for source, target, attributes in graph.edges(data=True): # if value/width not specified directly, and weight is specified, set 'value' to 'weight' if 'value' not in attributes and 'width' not in attributes and 'weight' in attributes: # place at key 'value' the weight of the edge attributes['value'] = attributes['weight'] # add the edge sna_visualisation.add_edge(source, target, **attributes) # If not work in production mode, show buttons if not prd_mode: sna_visualisation.show_buttons() if prd_mode: # Options are set by exporting them from the non prd mode for the specific graph originally created # You may need to change these for your graph sna_visualisation.set_options(""" var options = { "nodes": { "borderWidth": 3, "color": { "border": "rgba(0,0,0,1)", "background": "rgba(103,116,127,1)", "highlight": { "border": "rgba(0,0,0,1)", "background": "rgba(252,255,252,1)" } }, "font": { "size": 16, "strokeWidth": 5 }, "size": 10 }, "edges": { "color": { "inherit": true }, "smooth": false }, "physics": { "barnesHut": { "gravitationalConstant": -23350 }, "minVelocity": 0.75 } } """) # Save web page and return graph object return sna_visualisation.show("sna.html")
def draw_graph(networkx_graph, notebook=True, output_filename='graph.html', show_buttons=False, only_physics_buttons=False): """ This function accepts a networkx graph object, converts it to a pyvis network object preserving its node and edge attributes, and both returns and saves a dynamic network visualization. Valid node attributes include: "size", "value", "title", "x", "y", "label", "color". (For more info: https://pyvis.readthedocs.io/en/latest/documentation.html#pyvis.network.Network.add_node) Valid edge attributes include: "arrowStrikethrough", "hidden", "physics", "title", "value", "width" (For more info: https://pyvis.readthedocs.io/en/latest/documentation.html#pyvis.network.Network.add_edge) Args: networkx_graph: The graph to convert and display notebook: Display in Jupyter? output_filename: Where to save the converted network show_buttons: Show buttons in saved version of network? only_physics_buttons: Show only buttons controlling physics of network? """ # import from pyvis import network as net # make a pyvis network pyvis_graph = net.Network(notebook=notebook) pyvis_graph.width = '950px' # for each node and its attributes in the networkx graph for node, node_attrs in networkx_graph.nodes(data=True): pyvis_graph.add_node(node, **node_attrs) # for each edge and its attributes in the networkx graph for source, target, edge_attrs in networkx_graph.edges(data=True): # if value/width not specified directly, and weight is specified, set 'value' to 'weight' if not 'value' in edge_attrs and not 'width' in edge_attrs and 'weight' in edge_attrs: # place at key 'value' the weight of the edge edge_attrs['value'] = edge_attrs['weight'] # add the edge pyvis_graph.add_edge(source, target, **edge_attrs) # turn buttons on if show_buttons: if only_physics_buttons: pyvis_graph.show_buttons(filter_=['physics']) else: pyvis_graph.show_buttons() # return and also save return pyvis_graph.show(output_filename)
def draw_vis(M, **kwargs): # pragma: nocover from pyvis import network as net N = net.Network(**kwargs) for i, j, v in M: N.add_node(i, i, title=str(i)) N.add_node(j, j, title=str(j)) N.add_edge(i, j, value=str(v)) return N
def plot_triangle_relations(G, node): """ Plot all triangle relationships for a given node. """ triangle_nbrs = get_triangle_neighbors(G, node) triangle_nbrs.add(node) g = G.subgraph(triangle_nbrs) t = network.Network(height="200px", width="100%", heading = 'Triangles around ' + str(node), notebook = True) t.from_nx(g) t.set_options(""" options = { "nodes": { "color": { "highlight": { "border": "rgba(0,0,0,1)", "background": "rgba(90,255,84,1)" } } }, "edges": { "arrows": { "to": { "enabled": false }, "from": { "enabled": false } }, "color": { "inherit": true }, "smooth": false }, "physics": { "minVelocity": 0.75 } } """) return t.show('triangle.html')
def plot_network_pyvis(Y, labels=None, output_name='network_vis.html', is_directed=False, in_notebook=False, names=None, height="550px", width="100%", **kwargs): """Use the pyvis plotting library to display a network.""" network = pyvis.Network(height=height, width=width, notebook=in_notebook, directed=is_directed, **kwargs) # import graph if is_directed: nx_graph = nx.from_numpy_array(Y, create_using=nx.DiGraph) else: nx_graph = nx.from_numpy_array(Y) network.from_nx(nx_graph) if labels is not None: # integer encode labels encoder = LabelEncoder().fit(labels) n_groups = encoder.classes_.shape[0] # add node colors if n_groups <= 20: colors = get_color20() else: colors = sns.color_palette('husl', n_colors=n_groups) colors = np.asarray([to_hex(c) for c in colors]) for node in network.nodes: if names is not None: node['label'] = names[node['id']] node['color'] = colors[encoder.transform([labels[node['id']]])[0]] # display network.barnes_hut() return network.show(output_name)
def show_pyvis(self, graph, node_label=None): nt = net.Network(notebook=True, directed=True) # nt.from_nx(graph) nt.set_edge_smooth('straightCross') length_dict = nx.single_source_dijkstra_path_length(graph.to_undirected(), 1, 3, weight=1) color_dict = {0: 'red', 1: 'lightblue', 2: 'lightgreen'} for node in graph.nodes(data=True): if node_label is not None: nt.add_node(node[0], str(node[1][node_label]), color=color_dict[length_dict[node[0]]], shape='circle') else: nt.add_node(node[0], node[0], color=color_dict[length_dict[node[0]]], shape='circle') for o, i, l in graph.edges(data=True): nt.add_edge(o, i, label=str(round(l['edge_feat0'], 2))) return nt
def visualize(G, sg, name='attack-graph.html'): N = pvnet.Network(height='100%', width='100%', bgcolor='#222222', font_color='white', directed=True) opts = ''' var options = { "physics": { "forceAtlas2Based": { "gravitationalConstant": -100, "centralGravity": 0.01, "springLength": 100, "springConstant": 0.09, "avoidOverlap": 1 }, "minVelocity": 0.75, "solver": "forceAtlas2Based", "timestep": 0.22 } } ''' N.set_options(opts) for n in G: if n in sg: # if the node is part of the sub-graph color = 'green' size = 40 else: color = 'red' size = 30 N.add_node(n, label=n, color=color, size=size) for e in G.edges(): if e in sg.edges(): # if the edge is part of sub-graph color = 'green' width = 5 else: color = 'red' width = 1 N.add_edge((e[0]), (e[1]), color=color, width=width) return N.show(name)
def routinenodes(): #st.title("Nodos receptores Mama Duck") #st.write("A continución se muestra la distribución de nodos de Mama Duck, sus interconexiones e información") g=net.Network(height='400px', width='60%') colacolores=['teal', 'yellowgreen','purple','blue']#para que muestre colores distintos en cada nodo, hare un pop() for i in range(len(jn1)): #issue: no detecta los saltos de linea g.add_node(i+1,title=jn1.get(str(strindices[i]))[0].get('name')+ """\n"""+ """Status: """+jn1.get(str(strindices[i]))[0].get('status')+ """ Risk index:"""+str(jn1.get(str(strindices[i]))[0].get('risks')[0]),color=colacolores.pop(),borderWidthSelected=3,labelHighlightBold=True) for sti in strindices: for s in range(len(jn1.get(sti)[0]['conections'])): aux=jn1.get(sti)[0]['conections'] g.add_edge(int(sti),int(aux[s]),color='black') #guardo grafico g.save_graph('templates/graph.html')#en un archivo return render_template('graph.html')
def create_graph(self, file_name): cluster_sizes = np.array([len(i) for i in self.clusters]) max_nodes = max(cluster_sizes) min_nodes = min(cluster_sizes) g = net.Network(GetSystemMetrics(1), GetSystemMetrics(0), bgcolor="#222222") g.add_nodes(nodes = range(0, len(self.clusters), 1), size = [((i - min_nodes + len(self.clusters)) / (max_nodes - min_nodes)) * 100 for i in cluster_sizes], title = ["Contains " + str(len(x)) + " elements" for x in self.clusters], label = [' '] * len(self.clusters), color = ['#%02x%02x%02x' % (255, 255 - int(i / max_nodes * 255), 0) for i in cluster_sizes]) for i in range(0, len(self.clusters)): for j in range(i + 1, len(self.clusters)): if self.clusters[i].intersection(self.clusters[j]): g.add_edge(i, j, color = '#ffdd00') g.set_options(""" var options = { "nodes": { "shadow": { "enabled": true } }, "edges": { "color": { "inherit": true }, "smooth": true }, "physics": { "barnesHut": { "centralGravity": 0, "springLength": 1, "springConstant": 0.01, "avoidOverlap": 0.5 }, "minVelocity": 0.75 } } """) g.show(file_name) return g
def main(): investments = pd.read_csv("data/investments.csv") offices = pd.read_csv("data/offices.csv") objects = pd.read_csv("data/objects.csv", low_memory=False) nt = net.Network("1000px", "1000px") state_code = 'WY' investments = filter_by_state(investments, offices, state_code) state_companies = get_state_companies(state_code) num_companies = len(state_companies) nodes = get_nodes_df(nt) company_names = get_company_names(objects, nodes_df, num_companies) company_categories = get_company_categories(objects, nodes_df, num_companies) nodes_investments = get_nodes_investments(nt, num_companies, state_investments) nt = add_funds_edges(nt, nodes_investments, company_names, company_categories, state_companies, num_companies) create_graph(nt, state_code)
def plot_node(graph, node_id): local_graph = [] for neightbor in graph.neighbors(node_id): local_graph = local_graph + [n for n in graph.neighbors(neightbor)] local_graph = list(set(local_graph)) # make list unique subgraph = graph.subgraph(local_graph) # plot subgraph nt = net.Network(notebook=True, directed=True) nt.from_nx(subgraph) nt.set_edge_smooth('straightCross') length_dict = nx.single_source_dijkstra_path_length(subgraph, node_id, 2, weight=1) color_dict = {0: 'red', 1: 'lightblue', 2: 'lightgreen'} for node in nt.nodes: node["color"] = color_dict[length_dict[node['id']]] node['shape'] = 'circle' for edge in nt.edges: edge['label'] = round(edge['weight'], 2) nt.toggle_physics(False) return nt
def Display_Interactive_Chart(G): network = net.Network(notebook=True) network.set_options("""var_options = { "edges": { "color": { "inherit": true }, "smooth": false }, "interaction": { "navigationButtons": true }, "physics": { "minVelocity": 0.75, "solver": "repulsion" } }""") network.prep_notebook() network.height = '760px' network.width = '100%' network.from_nx(G) network.show("example2.html") return network
# st.pyplot(fig) # st.header('test') # def read_json_file(filename): # with open(filename) as f: # js_graph = json.load(f) # return json_graph.node_link_graph(js_graph) ##G = read_json_file('/content/data.json') # G = read_json_file('FootballJan2021.json') # st.write(G) g4 = net.Network( directed=True, height="1000px", width="1200px", notebook=True, heading="Football" ) g4.from_nx(G) # g4.show_buttons(filter_=['physics']) g4.show("wikiOutput.html") # display(HTML('karate.html')) HtmlFile = open("karate.html", "r") source_code = HtmlFile.read() components.html(source_code, height=1000, width=800) st.stop() ###### bokeh experiments bokeh experiments bokeh experiments bokeh experiments
''' from pyvis.network import Network net = Network(notebook=True) net.add_node(1, label='Alex') net.add_node(2, label='Cathy') #net.from_nx(G) net.show('nodes.html') ''' from pyvis import network as net import networkx as nx g = net.Network('800px', '1000px', notebook=True) g.add_node(0, label='Birkbeck', color='Crimson', value=200, shape='triangle') g.add_node(1, label='UCL', color='Crimson', value=200, shape='triangle') g.show('nodes.html')
if nv1 > -1 and commutes(nv1, S): # commutes(i, S): # Find neighbor with vertex i changed S0 = S.copy() # Copy created because otherwise, S is mutated in all stack frames S0.append(nv1) getGens(v1, i+1, S0, N) return # *********************************************************************************** # # ***** Main Program ******** # f = open("samplegraph.txt", "r") # generate base graph bg = net.Network() global n, k, adj, RS n = int(f.readline()) # first line states number of vertices of base graph k = int(f.readline()) # second line states number of colors adj = [] RS = [] # generate base graph and adjacency matrix for i in range(n): bg.add_node(i) neighbors = f.readline().split(" ") # read a line of the adjacency matrix adj.append([]) for j in range(i): if int(neighbors[j]) > 0: bg.add_edge(i, j) print(bg.num_edges())
left_on=['symbol_x', 'symbol_y'], right_on=['symbol_x', 'symbol_y']) new_df2 = new_df maxdf = new_df2.groupby(['company_name_x'])['freq'].max() new_df = new_df[(new_df.freq > 2)] ####################################################################################################################################################################### ####################################################################################################################################################################### ####################################################################################################################################################################### class_net = net.Network(height="100%", width="100%", bgcolor="#222222", font_color="white", notebook=False) # set the physics layout of the network class_net.barnes_hut() #got_data = pd.read_csv("https://www.macalester.edu/~abeverid/data/stormofswords.csv") new_df['symbol_x'] = new_df.symbol_x.astype(str) new_df['symbol_y'] = new_df.symbol_y.astype(str) new_df['sector_x'] = new_df.sector_x.astype(str) new_df['sector_y'] = new_df.sector_y.astype(str) #new_df['dept'] = new_df.dept.astype(str) #new_df['dept_2'] = new_df.dept_2.astype(str) sources = new_df.iloc[:, 2] targets = new_df.iloc[:, 3]
def plot_interactive(networkx_pickle): network_width = "1080px" network_height = "1080px" nxg = nx.read_gpickle(networkx_pickle) # set attributes for visualisation from clearly labelled attributes clean_nx = nx.Graph() metadata_values = set() for node in nxg.nodes.data(): if 'metadata' in node[1]: metadata_group = node[1]['metadata'] metadata_values.update([metadata_group]) clean_nx.add_node(node[0], title=f"{node[0].title()}: {metadata_group}", label=' ', group=metadata_group) else: clean_nx.add_node(node[0], title=node[0].title(), label=' ') max_edge_weight = max([x[2]['unique_genes'] for x in nxg.edges.data()]) edge_padding = 5 for edge in nxg.edges.data(): edge_width = 2.5 data = edge[2] if data['type'] == 'vf_only': clean_nx.add_edge(edge[0], edge[1], width=edge_width, color='orange', length=max_edge_weight - data['unique_genes'] + edge_padding, group=data['type'], title=f"Unique Shared Genes: {data['unique_genes']}; AMR: {data['amr_set']}; VF: {data['vf_set']}") elif data['type'] == 'amr_only': clean_nx.add_edge(edge[0], edge[1], width=edge_width, color='green', length=max_edge_weight - data['unique_genes'] + edge_padding, group=data['type'], title=f"Unique Shared Genes: {data['unique_genes']}; AMR: {data['amr_set']}; VF: {data['vf_set']}") elif data['type'] == 'amr_and_vf': clean_nx.add_edge(edge[0], edge[1], width=edge_width, color='purple', length=max_edge_weight - data['unique_genes'] + edge_padding, group=data['type'], title=f"Unique Shared Genes: {data['unique_genes']}; AMR: {data['amr_set']}; VF: {data['vf_set']}") else: clean_nx.add_edge(edge[0], edge[1], width=edge_width, color='black', length=max_edge_weight - data['unique_genes'] + edge_padding, group=data['type'], title=f"Unique Shared Genes: {data['unique_genes']}; AMR: {data['amr_set']}; VF: {data['vf_set']}") # add legends node_step = 70 node_x = -int(network_width.replace('px', '')) / 2 + 50 node_y = -int(network_height.replace('px', '')) /2 + 50 if len(metadata_values) > 0: clean_nx.add_node('Node Legend', label="Node Legend", shape='box', x=node_x, y=node_y, fixed=True, physics=False) for node in metadata_values: node_y += node_step clean_nx.add_node(node, label=node, group=node, x=node_x, y=node_y, fixed=True, physics=False) edge_labels = {'green': 'AMR in shared genes', 'orange':'VF in shared genes', 'purple': 'AMR & VF in shared genes', 'black': 'Non-AMR/VF shared genes'} edge_x = int(network_width.replace('px', '')) / 2 edge_y = -int(network_height.replace('px', '')) /2 + 50 if len(metadata_values) > 0: edge_step = 25 else: edge_step = 50 clean_nx.add_node('Edge Legend', label="Edge Legend", shape='box', x=edge_x, y=edge_y, fixed=True, physics=False) for colour, label in edge_labels.items(): edge_y += edge_step clean_nx.add_node(label, label=label, shape='square', color=colour, x=edge_x, y=edge_y, fixed=True, physics=False) g = net.Network(height=network_height, width=network_width, heading="Shared Gene Network") g.set_options('''var options = { "edges": { "arrowStrikethrough": false, "color": { "inherit": true }, "smooth": false }, "interaction": { "hover": true, "navigationButtons": true, "tooltipDelay": 175 } } ''') g.from_nx(clean_nx) g.write_html('network.html')
if newNode != curNode: newNode.mergePredcessorNodesFrom(curNode) else: newNode = reach_petrigraph.addNode(newState, curNode) reach_nxgraph.add_edge(curNode.getName(), newNode.getName(), label=trans.getLabel()) curNode.isChecked = True # if the graph is infinite, we cant create it, otherwise we can if not isInfinite: print("\nPlotting Reachability Graphs...") reach_pyvisgraph = pvnet.Network(directed=True, width=PYVISGRAPH_W, height=PYVISGRAPH_H, heading="Reachability graph") reach_pyvisgraph_workflow = pvnet.Network( directed=True, width=PYVISGRAPH_W, height=PYVISGRAPH_H, heading="Reachability graph (Workflow)") for node in reach_nxgraph.nodes(): nodeData = reach_petrigraph.getNodeWithName(node) nodeName = nodeData.getName() nodeLabel = nodeData.getGraphLabel() nodeColor = NODECOLOR_FIRST if node == list( reach_nxgraph.nodes())[0] else NODECOLOR_GENERIC nodeColor = NODECOLOR_LAST if node == list( reach_nxgraph.nodes())[-1] else nodeColor reach_pyvisgraph.add_node(nodeName,
def draw_graph3(networkx_graph, notebook=False, output_filename='graph_files/graph.html', show_buttons=True, only_physics_buttons=False): """ This function accepts a networkx graph object, converts it to a pyvis network object preserving its node and edge attributes, and both returns and saves a dynamic network visualization. Valid node attributes include: "size", "value", "title", "x", "y", "label", "color". (For more info: https://pyvis.readthedocs.io/en/latest/documentation.html#pyvis.network.Network.add_node) Valid edge attributes include: "arrowStrikethrough", "hidden", "physics", "title", "value", "width" (For more info: https://pyvis.readthedocs.io/en/latest/documentation.html#pyvis.network.Network.add_edge) Args: networkx_graph: The graph to convert and display notebook: Display in Jupyter? output_filename: Where to save the converted network show_buttons: Show buttons in saved version of network? only_physics_buttons: Show only buttons controlling physics of network? """ # make a pyvis network pyvis_graph = net.Network(notebook=notebook, directed=True, width="100%", height="100%") colors_used = [] r = lambda: random.randint(0, 255) # for each node and its attributes in the networkx graph for node, node_attrs in networkx_graph.nodes(data=True): color = '#%02X%02X%02X' % (r(), r(), r()) while color in colors_used: color = '#%02X%02X%02X' % (r(), r(), r()) colors_used.append(color) node_attrs['title'] = node node_attrs['color'] = color pyvis_graph.add_node(node, **node_attrs) # for each edge and its attributes in the networkx graph for source, target, edge_attrs in networkx_graph.edges(data=True): title = "" data = pyvis_graph.get_edges() print("source {}, target {}, edge_attrs {}".format( source, target, edge_attrs)) # if value/width not specified directly, and weight is specified, set 'value' to 'weight' if not 'value' in edge_attrs and not 'width' in edge_attrs and 'depth' in edge_attrs: # place at key 'value' the weight of the edge # edge_attrs['title']= "From {} to {} {}".format(source, target, edge_attrs['depth']) title = "Parent: {} Child: {}. Depths: {}".format( source, target, edge_attrs['depth']) # add the edge for d in data: if d['from'] == target and d['to'] == source: # Found a direction thingy title += "<br>" + d['title'] break edge_attrs['title'] = title pyvis_graph.add_edge(source, target, **edge_attrs) # turn buttons on # if show_buttons: # if only_physics_buttons: # pyvis_graph.show_buttons(filter_=['physics']) # else: # pyvis_graph.show_buttons() options = """ var options = { "nodes": { "physics": false, "size": 12 }, "edges": { "arrowStrikethrough": false, "color": { "inherit": true }, "physics": false, "smooth": false }, "physics": { "minVelocity": 0.75 } } """ pyvis_graph.set_options(options) # return and also save print(pyvis_graph.num_nodes()) pyvis_graph.show(output_filename) return pyvis_graph
def plot_relation(g): vis = net.Network(notebook=True) vis.from_nx(g) vis.show("test.html") return vis
def update_network(n_clicks,Account_1,Account_2,amount_range,start_date,end_date): if ((Account_1 is None) or (Account_2 is None) or (start_date is None) or (end_date is None)): print('Preventing update of network') raise PreventUpdate sd=datetime.strptime(start_date.split(' ')[0],'%Y-%m-%d').date() ed=datetime.strptime(end_date.split(' ')[0],'%Y-%m-%d').date() granular_bank_data=df[(df['datee'] >= sd) & (df['datee'] <= ed) & (df['amount']>=amount_range[0]) & (df['amount']<=amount_range[1])] tot_bank=filter_df(Account_1,sd,ed,amount_range[0],amount_range[1]) """granular_bank_data=bank_data[(bank_data['datee'] >= sd) & (bank_data['datee'] <= ed)] sent_bank=granular_bank_data[granular_bank_data['originn']==Account_1] recieved_bank=granular_bank_data[granular_bank_data['dest']==Account_1] tot_bank=pd.concat([sent_bank,recieved_bank]) edges = pd.DataFrame({'source': tot_bank['originn'],'target':tot_bank['dest'] ,'weight': tot_bank['amount'] ,'color': ['g' if x<=200 else 'r' for x in tot_bank['amount']] })""" adj_data = tot_bank if Account_1 != Account_2: a_temp=filter_df(Account_2,sd,ed,amount_range[0],amount_range[1]) a=a_temp[(a_temp['originn']==Account_2) & (a_temp['dest'] != Account_1)] b=a_temp[(a_temp['dest']==Account_2) & (a_temp['originn'] != Account_1)] adj_data=pd.concat([adj_data,a]) adj_data=pd.concat([adj_data,b]) for i in adj_data['originn'].unique(): for j in adj_data['dest'].unique(): if i != Account_1 and j != Account_1 and i != Account_2 and j != Account_2: origin_i=granular_bank_data[(granular_bank_data['originn']== i) & (granular_bank_data['dest']== j)] adj_data=pd.concat([adj_data,origin_i]) two_edges=pd.DataFrame({'source': adj_data['originn'],'target':adj_data['dest'] ,'weight': adj_data['amount'] ,'color': ['green' if x<=100 else 'red' for x in adj_data['amount']] }) G_two_edge = nx.from_pandas_edgelist(two_edges,'source','target', edge_attr=['weight','color'],create_using=nx.MultiDiGraph()) output_filename='TwoEdge_net_updated.html' # make a pyvis network network_class_parameters = {"notebook": True, "height": "98vh", "width":"98vw", "bgcolor": None,"font_color": None, "border": 0, "margin": 0, "padding": 0} # pyvis_graph = net.Network(**{parameter_name: parameter_value for parameter_name, parameter_value in network_class_parameters.items() if parameter_value}, directed=True) sources = two_edges['source'] targets = two_edges['target'] weights = two_edges['weight'] color = two_edges['color'] edge_data = zip(sources, targets, weights, color) for e in edge_data: src = e[0] dst = e[1] w = e[2] c = e[3] pyvis_graph.add_node(src,title=src) pyvis_graph.add_node(dst,title=dst) pyvis_graph.add_edge(src,dst,value=w,color=c) #pyvis_graph.show_buttons(filter_=['nodes','edges','physics']) pyvis_graph.set_options(""" var options = { "nodes": { "borderWidthSelected": 3, "color": { "border": "rgba(43,124,233,1)", "background": "rgba(109,203,252,1)", "highlight": { "border": "rgba(55,123,233,1)", "background": "rgba(255,248,168,1)" } }, "font": { "size": 15, "face": "tahoma" }, "size": 17 }, "edges": { "arrowStrikethrough": false, "color": { "inherit": true }, "smooth": { "forceDirection": "none", "roundness": 0.35 } }, "physics": { "forceAtlas2Based": { "springLength": 100, "avoidOverlap": 1 }, "minVelocity": 0.75, "solver": "forceAtlas2Based", "timestep": 0.49 } } """) pyvis_graph.save_graph(output_filename) return open(output_filename, 'r').read()
def draw_graph3(networkx_graph,notebook=True,output_filename='graph.html',show_buttons=True,only_physics_buttons=False, height=None,width=None,bgcolor=None,font_color=None,pyvis_options=None, p_type=False): """ This function accepts a networkx graph object, converts it to a pyvis network object preserving its node and edge attributes, and both returns and saves a dynamic network visualization. Valid node attributes include: "size", "value", "title", "x", "y", "label", "color". (For more info: https://pyvis.readthedocs.io/en/latest/documentation.html#pyvis.network.Network.add_node) Valid edge attributes include: "arrowStrikethrough", "hidden", "physics", "title", "value", "width" (For more info: https://pyvis.readthedocs.io/en/latest/documentation.html#pyvis.network.Network.add_edge) Args: networkx_graph: The graph to convert and display notebook: Display in Jupyter? output_filename: Where to save the converted network show_buttons: Show buttons in saved version of network? only_physics_buttons: Show only buttons controlling physics of network? height: height in px or %, e.g, "750px" or "100% width: width in px or %, e.g, "750px" or "100% bgcolor: background color, e.g., "black" or "#222222" font_color: font color, e.g., "black" or "#222222" pyvis_options: provide pyvis-specific options (https://pyvis.readthedocs.io/en/latest/documentation.html#pyvis.options.Options.set) """ # import from pyvis import network as net # make a pyvis network network_class_parameters = {"notebook": notebook, "height": height, "width": width, "bgcolor": bgcolor, "font_color": font_color} pyvis_graph = net.Network(**{parameter_name: parameter_value for parameter_name, parameter_value in network_class_parameters.items() if parameter_value}) # for each node and its attributes in the networkx graph for node,node_attrs in networkx_graph.nodes(data=True): pyvis_graph.add_node(str(node), shape='image',**node_attrs) # for each edge and its attributes in the networkx graph for source,target,edge_attrs in networkx_graph.edges(data=True): # if value/width not specified directly, and weight is specified, set 'value' to 'weight' if not 'value' in edge_attrs and not 'width' in edge_attrs and 'weight' in edge_attrs: # place at key 'value' the weight of the edge edge_attrs['value']=edge_attrs['weight'] # add the edge pyvis_graph.add_edge(str(source),str(target), value = 50, **edge_attrs) # turn buttons on if show_buttons: if only_physics_buttons: pyvis_graph.show_buttons(filter_=['physics']) else: pyvis_graph.show_buttons() # pyvis-specific options if pyvis_options: pyvis_graph.set_options(pyvis_options) # fix physics collision pyvis_graph.toggle_physics(False) # pyvis_graph.barnes_hut() if p_type: pyvis_graph.set_options(''' var options = { "nodes": { "font": { "size": 0 } }, "edges": { "color": { "color": "rgba(0, 232, 54,1)", "highlight": "rgba(255,116,53,1)", "inherit": false }, "smooth": false }, "physics": { "enabled": false, "minVelocity": 0.75 } } ''') # return and also save return pyvis_graph.show(output_filename)
from pyvis import network as net from IPython.core.display import display, HTML ids = ['C', 'N', 'C', 'N', 'C', 'C', 'C', 'O', 'N', 'C', 'O', 'N', 'C', 'C'] xs = [ 2.776, 1.276, 0.3943, -1.0323, -1.0323, 0.3943, 0.7062, 2.1328, -0.4086, -1.8351, -2.9499, -2.147, -3.5736, -0.0967 ] ys = [ 0.0, 0.0, 1.2135, 0.75, -0.75, -1.2135, -2.6807, -3.1443, -3.6844, -3.2209, -4.2246, -1.7537, -1.2902, -5.1517 ] bonds = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [6, 8], [8, 9], [9, 10], [9, 11], [11, 12], [8, 13], [5, 1], [11, 4]] g3 = net.Network(height='400px', width='80%', heading='') g3.set_options(''' var options = { "nodes": { "borderWidth": 2, "borderWidthSelected": 4 }, "edges":{ "width":24 }, "physics": { "barnesHut": { "gravitationalConstant":-2000, "centralGravity": 0, "springLength": 60, "springConstant": 0.545,
from pyvis import network as net import streamlit as st from stvis import pv_static g = net.Network(height='500px', width='500px', heading='') g.add_node(1) g.add_node(2) g.add_node(3) g.add_edge(1, 2) g.add_edge(2, 3) pv_static(g)
def draw_graph3(networkx_graph, output_filename, notebook=False): """ This function accepts a networkx graph object, converts it to a pyvis network object preserving its node and edge attributes, and both returns and saves a dynamic network visualization. Valid node attributes include: "size", "value", "title", "x", "y", "label", "color". (For more info: https://pyvis.readthedocs.io/en/latest/documentation.html#pyvis.network.Network.add_node) Valid edge attributes include: "arrowStrikethrough", "hidden", "physics", "title", "value", "width" (For more info: https://pyvis.readthedocs.io/en/latest/documentation.html#pyvis.network.Network.add_edge) Args: networkx_graph: The graph to convert and display notebook: Display in Jupyter? output_filename: Where to save the converted network show_buttons: Show buttons in saved version of network? only_physics_buttons: Show only buttons controlling physics of network? """ # import from pyvis import network as net # make a pyvis network pyvis_graph = net.Network(height="750px", width="100%", bgcolor="#222222", font_color="white", notebook=notebook) # for each node and its attributes in the networkx graph for node, node_attrs in networkx_graph.nodes(data=True): pyvis_graph.add_node(str(node), **node_attrs) # for each edge and its attributes in the networkx graph for source, target, edge_attrs in networkx_graph.edges(data=True): # if value/width not specified directly, and weight is specified, set 'value' to 'weight' if not 'value' in edge_attrs and not 'width' in edge_attrs and 'weight' in edge_attrs: # place at key 'value' the weight of the edge edge_attrs['value'] = edge_attrs['weight'] # add the edge pyvis_graph.add_edge(str(source), str(target), **edge_attrs) #pyvis_graph.show_buttons(filter_=['physics']) #use the repulsion solver # pyvis_graph.hrepulsion(node_distance=420, central_gravity=0.8, spring_length=420, spring_strength=1, damping=0) pyvis_graph.set_options(""" var options = { "configure": { "enabled": true, "filter": [ "physics" ] }, "edges": { "color": { "inherit": true }, "smooth": { "enabled": false, "type": "continuous" } }, "interaction": { "dragNodes": true, "hideEdgesOnDrag": false, "hideNodesOnDrag": false }, "physics": { "enabled": true, "barnesHut": { "springLength": 300, "damping": 0.6 }, "minVelocity": 0.75, "stabilization": { "enabled": true, "fit": true, "iterations": 1000, "onlyDynamicEdges": false, "updateInterval": 50 } } }""") # return and also save return pyvis_graph.save_graph(output_filename)