Python learning (32) --- networkx

1. Introduction to networkx

NetworkX provides graph (or network) data structures and graph algorithms, generators and drawing tools.

Function, method and variable names are lower_case_underscore (lower case, underscores indicate spaces between words).

 

Second, the basics

1. Import module

import networkx as nx

2. Picture / Network

Type of graph

  • Graph: Undirected graph without multiple edges. Ignore multiple edges between two nodes and allow the nodes to form loops by themselves.
  • DiGraph: directed graph without multiple edges
  • MultiGraph: There are multi-edge undirected graphs, allowing multiple undirected edges between pairs of nodes.
  • MultiDIGraph: directed graph with multiple edges

All graphs were allowed any available hashing objects as a node. Hashable objects include strings, tuples, integers, etc. Any edge attributes such as weights and labels can be associated with edges.

   Nx.Graph = G () # Create an empty network map 
   G = nx.DiGraph () 
   G = nx.MultiGraph () 
   G = nx.MultiDiGraph ()

Creation of graph: (three ways)

  1. Graph generators such as binomial_graph and powerlaw_graph
  2. Load data from a text source, such as nx.read_adjlist
  3. Create empty graphs independently and add points and edges

 

3. Nodes and edges

  • Node: integer / string / data structure describing the node
  • Edge: Keyword / value pair [You can use any keyword other than 'weight' to name the attribute, you can query the edge by this keyword]
# Add Point 
G.add_node ( ' A ' ) # add a point A 
G.add_node (1,1) # a coordinate point add 
G . Add_node ( Math . COS ) # Hashable the any CAN BE A Node

# Add edges
G.add_edge ( ' X ' , ' Y ' ) # add edges, starting at x, end point y, a default edge value. 1
G.add_edge (l, 3, weight = 0.9)
# add edges, starting at 1, the end point is 2, the weight value is 0.9
G.add_edge('y','x',function=math.cos) #Edge attributes can be anything
G.add_weight_edges_from ([( ' X ' , ' Y ' , 1.0)]) # third input is the weight 
# may be 
List = [[( ' A ' , ' B ' , 5.0), ( ' B ' , ' c ' , 3.0), ( ' a ' , ' c ' , 1.0 )] 
G.add_weight_edges_from ([(list)])

 

4. Graphic display

Need to import matplotlib
 import matplotlib.pyplot as plt 

nx.draw (G) 
# nx.draw_networkx (G) 

plt.show ()

#If you want to make the graphics more beautiful
nx.draw (G, pos = nx.random_layout (G), node_color = 'b', edge_color = 'r', with_labels = True, font_size = 18, node_size = 20)

pos refers to the layout mainly includes spring_layout, random_layout, circle_layout, shell_layout. node_color refers to the color of the node, rbykw, the same edge_color.
with_labels refers to whether the node displays the name, size indicates the size, font_color indicates the color of the word.

 

Guess you like

Origin www.cnblogs.com/Lee-yl/p/12684966.html