#!/usr/bin/env python # coding: utf-8 # # NetworkX # NetworkX is a Python language software package for the creation, manipulation, and study of the structure, dynamics, and function of complex networks. # # With NetworkX you can load and store networks in standard and nonstandard data formats, generate many types of random and classic networks, analyze network structure, build network models, design new network algorithms, draw networks, and much more. # # Library documentation: https://networkx.github.io/ # In[1]: import networkx as nx G = nx.Graph() # In[2]: # basic add nodes G.add_node(1) G.add_nodes_from([2, 3]) # In[3]: # add a group of nodes at once H = nx.path_graph(10) G.add_nodes_from(H) # In[4]: # add another graph itself as a node G.add_node(H) # In[5]: # add edges using similar methods G.add_edge(1, 2) e = (2, 3) G.add_edge(*e) G.add_edges_from([(1, 2), (1, 3)]) G.add_edges_from(H.edges()) # In[6]: # can also remove or clear G.remove_node(H) G.clear() # In[7]: # repeats are ignored G.add_edges_from([(1,2),(1,3)]) G.add_node(1) G.add_edge(1,2) G.add_node('spam') # adds node "spam" G.add_nodes_from('spam') # adds 4 nodes: 's', 'p', 'a', 'm' # In[8]: # get the number of nodes and edges G.number_of_nodes(), G.number_of_edges() # In[9]: # access graph edges G[1] # In[10]: G[1][2] # In[11]: # set an attribute of an edge G.add_edge(1,3) G[1][3]['color'] = 'blue' # In[12]: FG = nx.Graph() FG.add_weighted_edges_from([(1, 2, 0.125), (1, 3, 0.75), (2, 4, 1.2), (3, 4, 0.375)]) for n, nbrs in FG.adjacency_iter(): for nbr, eattr in nbrs.items(): data = eattr['weight'] if data < 0.5: print('(%d, %d, %.3f)' % (n, nbr, data)) # In[13]: # graph attribte G = nx.Graph(day='Friday') G.graph # In[14]: # modifying an attribute G.graph['day'] = 'Monday' G.graph # In[15]: # node attributes G.add_node(1, time='5pm') G.add_nodes_from([3], time='2pm') G.node[1]['room'] = 714 G.nodes(data=True) # In[16]: # edge attributes (weight is a special numeric attribute) G.add_edge(1, 2, weight=4.7) G.add_edges_from([(3, 4), (4, 5)], color='red') G.add_edges_from([(1, 2 ,{'color': 'blue'}), (2, 3, {'weight' :8})]) G[1][2]['weight'] = 4.7 G.edge[1][2]['weight'] = 4 # In[17]: # directed graph DG = nx.DiGraph() DG.add_weighted_edges_from([(1, 2 ,0.5), (3, 1, 0.75)]) DG.out_degree(1, weight='weight') # In[18]: DG.degree(1, weight='weight') # In[19]: DG.successors(1) # In[20]: DG.predecessors(1) # In[21]: # convert to undirected graph H = nx.Graph(G) # In[22]: # basic graph drawing capability get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt nx.draw(G)