Realization of drawing complex network diagram with python networkx packet
- 2021-07-13 05:43:00
- OfStack
1. Create a diagram
import networkx as nx
g = nx.Graph()
g.clear() # Empty the elements on the diagram
All the operations of building complex network diagrams are basically performed around this g.
2. Nodes
The name of a node can be of any data type. Adding 1 node is
g.add_node(1)
g.add_node("a")
g.add_node("spam")
Adding a group of nodes means building a list of nodes in advance and adding them once, which is 1-dimensional with the operation of adding edges later.
g.add_nodes_from([2,3])
or
a = [2,3]
g.add_nodes_from(a)
One important point to note here is that for add_node plus a dot, the string is only a node with the name of the whole string added. But for
add_nodes_from Plus 1 Group points, the string represents the addition of each 1 Multiple nodes represented by each character, exp :
g.add_node("spam") # Added 1 A person named spam Node of
g.add_nodes_from("spam") # Added 4 Node named s,p,a,m
g.nodes() # You can put the above 5 Print out the nodes to see
Nodes with 1 group of consecutive numbers starting from 0
H = nx.path_graph(10)
g.add_nodes_from(H) # Will 0~9 Joined node
# But do not use g.add_node(H)
Delete Node
Same as adding nodes
g.remove_node(node_name)
g.remove_nodes_from(nodes_list)
3. Edge
Edge is composed of tuples corresponding to the name of the node, plus one edge
g.add_edge(1,2)
e = (2,3)
g.add_edge(*e) # Direct g.add_edge(e) The data type is wrong, * Is to take out the elements in the tuple
Add 1 set of edges
g.add_edges_from([(1,2),(1,3)])
g.add_edges_from([("a","spam") , ("a",2)])
Adding 1 series of continuous edges through nx.path_graph (n)
n = 10
H = nx.path_graph(n)
g.add_edges_from(H.edges()) # Added 0~1,1~2 ... n-2~n-1 Such a n-1 Strip continuous edges
Delete Edge
The operation of adding edges in the same way
g.remove_edge(edge)
g.remove_edges_from(edges_list)
4. View points and edges on a graph
g.add_node(1)
g.add_node("a")
g.add_node("spam")
0
method | explanation |
---|---|
Graph.has_node(n) | Return True if the graph contains the node n. |
Graph.__contains__(n) | Return True if n is a node, False otherwise. |
Graph.has_edge(u, v) | Return True if the edge (u,v) is in the graph. |
Graph.order() | Return the number of nodes in the graph. |
Graph.number_of_nodes() | Return the number of nodes in the graph. |
Graph.__len__() | Return the number of nodes. |
Graph.degree([nbunch, weight]) | Return the degree of a node or nodes. |
Graph.degree_iter([nbunch, weight]) | Return an iterator for (node, degree). |
Graph.size([weight]) | Return the number of edges. |
Graph.number_of_edges([u, v]) | Return the number of edges between two nodes. |
Graph.nodes_with_selfloops() | Return a list of nodes with self loops. |
Graph.selfloop_edges([data, default]) | Return a list of selfloop edges. |
Graph.number_of_selfloops() | Return the number of selfloop edges. |
5. Attribute settings for diagrams
Assign initial attributes to a graph
g = nx.Graph(day="Monday")
g.graph # {'day': 'Monday'}
Modify the properties of a graph
g.graph['day'] = 'Tuesday'
g.graph # {'day': 'Tuesday'}
6. Point property settings
g.add_node(1)
g.add_node("a")
g.add_node("spam")
3
7. Edge property settings
From the introduction of g [1] above, we can see that the attributes of edges are displayed in {}, and we can change the attributes according to this show
g.add_node(1)
g.add_node("a")
g.add_node("spam")
4
8. Different types of graphs (directed graph Directed graphs, double edge graph Multigraphs)
Directed graphs
g.add_node(1)
g.add_node("a")
g.add_node("spam")
5
Multigraphs
Literally, this complex network diagram allows you to have multiple edges between the same nodes
g.add_node(1)
g.add_node("a")
g.add_node("spam")
6
9. Graph traversal
g = nx.Graph()
g.add_weighted_edges_from([(1,2,0.125),(1,3,0.75),(2,4,1.2),(3,4,0.375)])
for n,nbrs in g.adjacency_iter(): #n Represents every 1 A starting point, nbrs Yes 1 Each dictionary, each dictionary 1 Elements contain the attributes of the point connected by the starting point and the edge of the two points
print n, nbrs
for nbr,eattr in nbrs.items():
# nbr Representation heel n Connected points, eattr Represents the property collection of the edge of these two points, where only the weight If you also set up color , then you can pass eattr['color'] Access to the corresponding color Element
data=eattr['weight']
if data<0.5: print('(%d, %d, %.3f)' % (n,nbr,data))
10. Graph generation and some operations on the graph
The following operations are all methods within the networkx package
subgraph(G, nbunch) - induce subgraph of G on nodes in nbunch
union(G1,G2) - graph union
disjoint_union(G1,G2) - graph union assuming all nodes are different
cartesian_product(G1,G2) - return Cartesian product graph
compose(G1,G2) - combine graphs identifying nodes common to both
complement(G) - graph complement
create_empty_copy(G) - return an empty copy of the same graph class
convert_to_undirected(G) - return an undirected representation of G
convert_to_directed(G) - return a directed representation of G
11. Graphic analysis
g.add_node(1)
g.add_node("a")
g.add_node("spam")
9
By constructing the weight graph, the shortest distance can be calculated directly and quickly by using dijkstra_path () interface
>>> G=nx.Graph()
>>> e=[('a','b',0.3),('b','c',0.9),('a','c',0.5),('c','d',1.2)]
>>> G.add_weighted_edges_from(e)
>>> print(nx.dijkstra_path(G,'a','d'))
['a', 'c', 'd']
12. Mapping
Here are four ways to construct graphs. Choose one of them
nx.draw(g)
nx.draw_random(g) # Point random distribution
nx.draw_circular(g) # Distribution formation of points 1 Ring
nx.draw_spectral(g)
Finally, the graphics are displayed
import matplotlib.pyplot as plt
plt.show()
Save the picture to
nx.draw(g)
plt.savefig("path.png")
Modify node color, edge color
g = nx.cubical_graph()
nx.draw(g, pos=nx.spectral_layout(g), nodecolor='r', edge_color='b')
plt.show()
13. Choice of graphic types
Graph Type | NetworkX Class |
---|---|
简单无向图 | Graph() |
简单有向图 | DiGraph() |
有自环 | Grap(),DiGraph() |
有重边 | MultiGraph(), MultiDiGraph() |
reference: https://networkx.github. io/documentation/networkx-1. 10/reference/classes. html