type of diagram
The graph class is the base class of an key/value graph, which can have its own attributes or parameters, does not contain heavy edges, allows loops, nodes can be any hash of the Python object, and nodes and edges can hold the property pair. The constructor for this class is graph (data=none,**attr), where data can be a list of edges, or any Networkx graph object, and the default is none;attr is a keyword argument, such as a key=value-to-form property.
Multigraph are non-direction graphs that can have heavy edges, others are similar to graph. Its constructor multigraph (Data=none, *attr).
Digraph is the base class of the graph, the graph can have its own attributes or parameters, does not contain the heavy edges, allowing the loop; the node can be any hash Python object, and the edges and nodes can contain Key/value property pairs. The constructor for the class digraph (data=none,**attr), where data can be a list of edges, or any of the Networkx graph objects, the default is that none;attr is a keyword parameter, such as Key=value-to-form properties.
Multidigraph is a forward graph that can have heavy edges, others are similar to digraph. Its constructor multidigraph (Data=none, *attr).
Creation of graphs
Import Networkx as NxG # created an empty diagram with no nodes and edges
Graph graph here consists of a series of nodes and node pairs (or edges, links). In Networx, a node can be any object that can be hashed, including text strings, pictures, XML objects, graph, and custom nodes.
The node of the graph
Graphs can grow in a variety of ways. NETWORKX provides multiple graph generation capabilities for reading and writing diagrams.
Add one node at a time:
G.add_node (1)
Adding nodes through containers that contain nodes: #可以是列表, dictionaries, certain lines of files, other diagrams, etc.
List
G.add_nodes_from ([2,3])
Other diagrams
# H is a graph object here
Side of the graph
Add one edge at a time: >>>g.add_edge
By adding a container containing edges:
List >>>g.add_edges_from ([(+), (1,3)])
Edge Collection >>>g.add_edges_from (H.edges ()) #H is also a graph here
Property
For graphs, edges and nodes can be key/value as their own properties, stored in the relevant dictionary. The associated dictionary is empty by default, but can be modified by add_edge,add_node or manipulation.
To add a graph's properties:
G=nx. Graph (day="Friday")
Add properties for a node: #主要的方法是add_node () and Add_nodes_from ()
G.add_node (1,time='5pm') # gives the node 1 plus attribute to time:5pmG.add_nodes_ From ([3], time='2pm'# for all nodes in the previous parameter, add property to time:2pm g.node[1][']=714 # Adds a property pair to Node 1 in G room:714
attributes for adding edges: #主要方法是add_edge (), Add_edges (), and G.edge
G.add_edge,'weight'# is an edge between 1 and 2, adding an attribute weight:4.7g.add_edges_from ([ (3,4), (4,5)],color='red'# Add properties to color:red g[1][2][' for connections 3 and 4, 4, and 5' weight']=4.7g.edge[1][2]['weight']=4
Other
Len (g) # returns the number of nodes in the G in G # Check if node n is in G, as in, returns True.
Related functions
Initialize: G=nx. Graph ()
Graph-related properties function:
Nx.degree (G)//Calculate the density of the graph, whose value is the number of sides m divided by the number of possible edges in the graph (i.e. n (n-1)/2)
Nx.degree_centrality (G)//node-degree center coefficient. The degree to which the node is represented in the graph is normalized by default, and its value is expressed as the node degree D (u) divided by n-1 (where n-1 is the constant used by normalization). This value may be greater than 1 because there may be loops.
Nx.closeness_centrality (G)//node distance center coefficient. The importance of the node in the graph by distance is usually the reciprocal of the average path of the node to the other nodes, which is also multiplied by the n-1. The larger the value, the closer the node is to other nodes, the higher the centrality.
Nx.betweenness_centrality (G)//node-number center coefficient. In an n-1 graph, this value is expressed as the number of the shortest path to the node divided by (() (n-2)/2); In a graph, the value is expressed as the number of shortest paths divided by ((n-1) (n-2).
Nx.transitivity (G)//The transitivity of the graph or network. In the figure or network, the two nodes that know the same node may also know the two sides, the calculation formula is the number of triangles in the map (the number of triples is the logarithm of the edge of the common vertex, so it is good number).
Nx.clustering (G)//graph or cluster coefficients of nodes in the network. The formula is: divide the number of edges between the two neighbor nodes of the node U (d (U) (d (U)-1)/2).
--------------------------------------------------------------------------------------------------------------- -------
--------------------------------------------------------------------------------------------------------------- -------
Ii. Building diagrams or networks
1. No direction diagram
In Pythonwin's shell, enter:
ImportNetworkx as NX#Import the Networkx package, rename it to NX in order to make a few letters lessG = NX. Graph ()#Create an empty graph GG.add_node (1)#Add a Node 1G.add_edge (2,3)#Add an edge 2-3 (implicitly adding two nodes 2, 3)G.add_edge (3,2)#for a graph without direction, Edge 3-2 and Edge 2-3 are considered to be an edgePrintG.nodes ()#Output ALL nodes: [1, 2, 3]PrintG.edges ()#output All edges: [(2, 3)]PrintG.number_of_edges ()#number of output edges: 1
This makes it possible to create a simple, non-graphic diagram. If your data is in a file, you can loop the read nodes and edges from the file into G.
2, the Map
The way to create a graph is basically similar to an image, except that in the second line of the code above, G = NX. Graph () is changed to G = NX. DiGraph (). It is important to note that at this point 3-2 and Edge 2-3 are added, it is considered to be two different sides (you can try to run the above code, see the results yourself).
At the same time, the graph and the graph can be converted to each other, using graph.to_undirected () and graph.to_directed () two methods respectively.
3. Weighted graph (Network)
Both the graph and the graph can give the edge weight, the method used is Add_weighted_edges_from, it accepts 1 or more triples [u,v,w] as parameters, where U is the starting point, V is the end point, W is the weight. For example:
G.add_weighted_edges_from ([(0,1,3.0), (1,2,7.5)])
Add 0-1 and 1-2 sides with weights of 3.0 and 7.5, respectively.
If you want to read the weights, you can use the Get_edge_data method, which accepts two parameters U and V, that is, the commencement point of the edge. For example:
Print G.get_edge_data # output {' Weight ': 7.5}, this is a dictionary structure that can be viewed in Python syntax to understand its usage.
Third, call graph algorithm
NETWORKX provides commonly used graph theory classical algorithms, such as DFS, BFS, shortest path, minimum spanning tree, maximum flow, etc., is very rich, if do not do complex network, only the work of mapping theory, can also apply networkx as a basic development package. Specific algorithm call method I will not introduce each,
Can browse NX's online manual http://networkx.lanl.gov/reference/algorithms.html,
Detailed Help documentation and examples are provided for each algorithm.
Here is an example of the shortest path algorithm:
Path=nx.all_pairs_shortest_path (g) # Call the multi-source shortest path algorithm to calculate the shortest path between all nodes in Figure G print path[0][2] # the shortest path sequence between output nodes 0 and 2: [0, 1, 2]
--------------------------------------------------------------------------------------------------------------- -------
--------------------------------------------------------------------------------------------------------------- -------
Third, network visualization
Scientific visualization is the use of computer graphics to create visual images that help people understand scientific concepts or results that take the form of complex and often large digital representations. Visualization is also important for complex network research, which helps to present or interpret complex network data and models, and then discover patterns, features, and relationships that are not easily found in data.
In my other blog post, "recommend a Web site for complex web visualization," The Www.visualcomplexity.com site, which has a large number of complex networks and complex systems, is a breathtaking and colourful picture. Some friends may wonder if these graphics are made using some professional graphic design software. In fact, by using NETWORKX, we can also create beautiful complex network graphics, which provide a very rich network visualization capabilities. The animation below is made from images downloaded from the NETWORKX website, and interested friends can go to the http://networkx.lanl.gov/gallery.html address to see the source code that generated the graphs.
In this note, I'll simply describe the basic way to draw complex network graphics using NETWORKX. Of course, I am also a beginner in this area, only a little understanding of some fur, hoping to play a role:)
First, the basic drawing process
In Networkx, drawing a network using the Nx.draw () method, it accepts at least one parameter: The network g that you want to draw. In fact, this method is very complex, it can specify more than 20 keyword parameters, the following will introduce some common parameters, we start with the simplest case, look at the following example:
import Networkx as NX # Imports Networkx package import matplotlib.pyplot as Plt # Import Drawing Package matplotlib (need to install, method see first note)G =nx.random_graphs.barabasi_albert_graph (100,1) # generate a BA scale-free network Gnx.draw (g) # Draw Network GPlt.savefig ("ba.png ") # Output Mode 1: Save image as a picture file in PNG format plt.show () # output Mode 2: Display this image in a window
The result of running the above code is as follows:
In this way, with just a few lines of code to complete a basic network drawing, and generated a rich form of functionality. The toolbar at the bottom left of the window can zoom in, zoom out, pan, save, and so on, you can try it yourself. At the same time, in the source file directory also generated a PNG format picture file, it can be inserted into the report or paper, is not very convenient?
Second, use style
The code above is simple, but the resulting graph is slightly monotonous. NETWORKX provides a range of styling parameters that can be used to decorate and beautify the graphic to achieve the desired effect. Commonly used parameters include:
-' node_size ': Specify the size of the node (default is 300, the unit is unknown, that is, the point that is so large)
-' Node_color ': specifies the color of the node (the default is red, you can easily identify the color with a string, such as ' R ' is red, ' B ' is green, etc., see the manual)
-The shape of the ' Node_shape ': node (the default is a circle, identified by the string ' o ', to see the manual)
-' alpha ' : Transparency (default is 1.0, opaque, 0 is fully transparent)
-' width ': Width of Edge (default = 1.0)
-' edge_color ': The Color of the edge (default is black)
-' style ': The style of the edge (default is implementation, Optional: solid|dashed|dotted, DASHDOT)
-' with_labels ': Whether the node is tagged (default is True)
-' Font_size ': node label font size (default is)
-' Font_color ': node label font color (default is black)
Flexible use of the above parameters, You can draw network graphics of different styles, for example: Nx.draw (g,node_size = 30,with_labels = False) is a network diagram that draws a node size of 30 without a label.
Third, use layout
Networkx provides layout capabilities for drawing network graphics, and you can specify the form of node arrangement. These layouts include:
Circular_layout: Nodes are evenly distributed on a ring
Random_layout: Nodes are randomly distributed
Shell_layout: Nodes are distributed on concentric circles
Spring_layout: Use the Fruchterman-reingold algorithm to arrange nodes (the algorithm I do not understand, like a multi-center radial)
Spectral_layout: The nodes are arranged according to the Laplace eigenvector of the graph? I'm not too sure. The
layout is specified with the POS parameter, for example: Nx.draw (G,pos = Nx.circular_layout (G)). In the previous note, four different models were drawn in four layouts, where you can see the effect, and no longer repeat the code here.
Alternatively, you can specify a single location (x, y coordinate) for each node in the diagram, but it is more complex than I have ever done. Interested friends can take a look at an example in the Networkx document: Http://networkx.lanl.gov/examples/drawing/knuth_miles.html.
Iv. adding text
Use the Plt.title () method to add a caption to a graphic that takes a string as a parameter, and the fontsize parameter to specify the size of the caption. For example: Plt.title ("BA Networks", FontSize = 20). If you want to add text anywhere, you can use the Plt.text () method. In fact, these functions (including the front of the graphic preservation and other functions) are not provided by Networkx, from the name of the package can be seen, these drawing functions are provided by the Matplotlib this package. Networkx just repackaged the functionality associated with complex network drawings, making it easier for users to call.
A point to add is that matplotlib does not directly support the Chinese text, if you want to export Chinese, go the formal method is still very troublesome (see http://blog.csdn.net/KongDong/archive/2009/07/10/4338826. aspx). But a smart Netizen has proposed a rescue solution: Change the font. As long as a Chinese font file (TTF file) renamed to Vera.ttf, copied to the Matplotlib font directory to overwrite the original file, you can output Chinese, detailed details see http://hi.baidu.com/ucherish/blog/item/ 63155e52b68c90070df3e3ff.html.
V. Summary
This note simply introduces the method of drawing complex network graph with networkx, in fact Networkx's cartographic ability is very strong (mainly matplotlib credit), this article introduces the function is only one of the most basic part, more function still waits for us to explore together. Re-recommend the http://networkx.lanl.gov/gallery.html on the drawing sample code, can understand the code, with the Networkx drawing should be difficult for you:)
Networkx of network analysis (reprint)