Networkx Reference
Networkx Reference
Release 2.5
1 Introduction 1
1.1 NetworkX Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Graph Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Graph Reporting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Drawing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.7 Data Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2 Graph types 7
2.1 Which graph class should I use? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Basic graph types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3 Graph Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
2.4 Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
3 Algorithms 141
3.1 Approximations and Heuristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
3.2 Assortativity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
3.3 Asteroidal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
3.4 Bipartite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
3.5 Boundary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
3.6 Bridges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
3.7 Centrality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
3.8 Chains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
3.9 Chordal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
3.10 Clique . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
3.11 Clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
3.12 Coloring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
3.13 Communicability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
3.14 Communities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
3.15 Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
3.16 Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
3.17 Cores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
3.18 Covering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
3.19 Cycles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
3.20 Cuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
3.21 D-Separation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
3.22 Directed Acyclic Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
3.23 Distance Measures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
3.24 Distance-Regular Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
i
3.25 Dominance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
3.26 Dominating Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
3.27 Efficiency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
3.28 Eulerian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
3.29 Flows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
3.30 Graph Hashing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
3.31 Graphical degree sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
3.32 Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
3.33 Hybrid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
3.34 Isolates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
3.35 Isomorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
3.36 Link Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
3.37 Link Prediction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
3.38 Lowest Common Ancestor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
3.39 Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
3.40 Minors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
3.41 Maximal independent set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
3.42 non-randomness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
3.43 Moral . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
3.44 Node Classification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
3.45 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
3.46 Planarity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
3.47 Planar Drawing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
3.48 Reciprocity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
3.49 Regular . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
3.50 Rich Club . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
3.51 Shortest Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
3.52 Similarity Measures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
3.53 Simple Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
3.54 Small-world . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
3.55 s metric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
3.56 Sparsifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
3.57 Structural holes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
3.58 Swap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
3.59 Threshold Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
3.60 Tournament . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
3.61 Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
3.62 Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
3.63 Triads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
3.64 Vitality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
3.65 Voronoi cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
3.66 Wiener index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
4 Functions 567
4.1 Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
4.2 Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
4.3 Edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
4.4 Self loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
4.5 Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
4.6 Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
4.7 Freezing graph structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
ii
5.2 Classic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
5.3 Expanders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
5.4 Lattice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
5.5 Small . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602
5.6 Random Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
5.7 Duplication Divergence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
5.8 Degree Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619
5.9 Random Clustered . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
5.10 Directed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
5.11 Geometric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
5.12 Line Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638
5.13 Ego Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
5.14 Stochastic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
5.15 AS graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642
5.16 Intersection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643
5.17 Social Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
5.18 Community . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
5.19 Spectral . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655
5.20 Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656
5.21 Non Isomorphic Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658
5.22 Triads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
5.23 Joint Degree Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 660
5.24 Mycielski . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
5.25 Harary Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664
5.26 Cographs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666
5.27 Interval Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
5.28 Sudoku . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
iii
9.7 GraphML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 736
9.8 JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740
9.9 LEDA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746
9.10 YAML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 747
9.11 SparseGraph6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 748
9.12 Pajek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 755
9.13 GIS Shapefile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757
10 Drawing 759
10.1 Matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759
10.2 Graphviz AGraph (dot) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 769
10.3 Graphviz with pydot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772
10.4 Graph Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 775
11 Randomness 785
12 Exceptions 787
12.1 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
13 Utilities 789
13.1 Helper Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
13.2 Data Structures and Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791
13.3 Random Sequence Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 792
13.4 Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 793
13.5 Cuthill-Mckee Ordering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797
14 Glossary 801
A Tutorial 803
A.1 Creating a graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
A.2 Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
A.3 Edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 804
A.4 Examining elements of a graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
A.5 Removing elements from a graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
A.6 Using the graph constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
A.7 What to use as nodes and edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
A.8 Accessing edges and neighbors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
A.9 Adding attributes to graphs, nodes, and edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807
A.10 Directed graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 808
A.11 Multigraphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 808
A.12 Graph generators and graph operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
A.13 Analyzing graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 810
A.14 Drawing graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811
Bibliography 815
Index 821
iv
CHAPTER
ONE
INTRODUCTION
The structure of NetworkX can be seen by the organization of its source code. The package provides classes for graph
objects, generators to create standard graphs, IO routines for reading in existing datasets, algorithms to analyze the
resulting networks and some basic drawing tools.
Most of the NetworkX API is provided by functions which take a graph object as an argument. Methods of the graph
object are limited to basic manipulation and reporting. This provides modularity of code and documentation. It also
makes it easier for newcomers to learn about the package in stages. The source code for each module is meant to be
easy to read and reading this Python code is actually a good way to learn more about network algorithms, but we have
put a lot of effort into making the documentation sufficient and friendly. If you have suggestions or questions please
contact us by joining the NetworkX Google group.
Classes are named using CamelCase (capital letters at the start of each word). functions, methods and variable
names are lower_case_underscore (lowercase with an underscore representing a space between words).
After starting Python, import the networkx module with (the recommended way)
To save repetition, in the documentation we assume that NetworkX has been imported this way.
If importing networkx fails, it means that Python cannot find the installed module. Check your installation and your
PYTHONPATH.
The following basic graph types are provided as Python classes:
Graph This class implements an undirected graph. It ignores multiple edges between two nodes. It does allow
self-loop edges between a node and itself.
DiGraph Directed graphs, that is, graphs with directed edges. Provides operations common to directed graphs, (a
subclass of Graph).
MultiGraph A flexible graph class that allows multiple undirected edges between pairs of nodes. The additional
flexibility leads to some degradation in performance, though usually not significant.
MultiDiGraph A directed version of a MultiGraph.
Empty graph-like objects are created with
>>> G = [Link]()
>>> G = [Link]()
>>> G = [Link]()
>>> G = [Link]()
1
NetworkX Reference, Release 2.5
All graph classes allow any hashable object as a node. Hashable objects include strings, tuples, integers, and more.
Arbitrary edge attributes such as weights and labels can be associated with an edge.
The graph internal data structures are based on an adjacency list representation and implemented using Python dictio-
nary datastructures. The graph adjacency structure is implemented as a Python dictionary of dictionaries; the outer
dictionary is keyed by nodes to values that are themselves dictionaries keyed by neighboring node to the edge at-
tributes associated with that edge. This “dict-of-dicts” structure allows fast addition, deletion, and lookup of nodes
and neighbors in large graphs. The underlying datastructure is accessed directly by methods (the programming in-
terface “API”) in the class definitions. All functions, on the other hand, manipulate graph-like objects solely via
those API methods and not by acting directly on the datastructure. This design allows for possible replacement of the
‘dicts-of-dicts’-based datastructure with an alternative datastructure that implements the same methods.
1.2 Graphs
The first choice to be made when using NetworkX is what type of graph object to use. A graph (network) is a collection
of nodes together with a collection of edges that are pairs of nodes. Attributes are often associated with nodes and/or
edges. NetworkX graph objects come in different flavors depending on two main properties of the network:
• Directed: Are the edges directed? Does the order of the edge pairs (𝑢, 𝑣) matter? A directed graph is specified
by the “Di” prefix in the class name, e.g. DiGraph(). We make this distinction because many classical graph
properties are defined differently for directed graphs.
• Multi-edges: Are multiple edges allowed between each pair of nodes? As you might imagine, multiple edges
requires a different data structure, though clever users could design edge data attributes to support this function-
ality. We provide a standard data structure and interface for this type of graph using the prefix “Multi”, e.g.,
MultiGraph().
The basic graph classes are named: Graph, DiGraph, MultiGraph, and MultiDiGraph
The next choice you have to make when specifying a graph is what kinds of nodes and edges to use.
If the topology of the network is all you care about then using integers or strings as the nodes makes sense and you
need not worry about edge data. If you have a data structure already in place to describe nodes you can simply use
that structure as your nodes provided it is hashable. If it is not hashable you can use a unique identifier to represent
the node and assign the data as a node attribute.
Edges often have data associated with them. Arbitrary data can be associated with edges as an edge attribute. If the
data is numeric and the intent is to represent a weighted graph then use the ‘weight’ keyword for the attribute. Some
of the graph algorithms, such as Dijkstra’s shortest path algorithm, use this attribute name by default to get the weight
for each edge.
Attributes can be assigned to an edge by using keyword/value pairs when adding edges. You can use any keyword to
name your attribute and can then query the edge data using that attribute keyword.
Once you’ve decided how to encode the nodes and edges, and whether you have an undirected/directed graph with or
without multiedges you are ready to build your network.
2 Chapter 1. Introduction
NetworkX Reference, Release 2.5
>>> elist = [(1, 2), (2, 3), (1, 4), (4, 2)]
>>> G.add_edges_from(elist)
>>> elist = [('a', 'b', 5.0), ('b', 'c', 3.0), ('a', 'c', 1.0), ('c', 'd', 7.3)]
>>> G.add_weighted_edges_from(elist)
Class views provide basic reporting of nodes, neighbors, edges and degree. These views provide iteration over the
properties as well as membership queries and data attribute lookup. The views refer to the graph data structure so
changes to the graph are reflected in the views. This is analogous to dictionary views in Python 3. If you want to
change the graph while iterating you will need to use e.g. for e in list([Link]):. The views provide
set-like operations, e.g. union and intersection, as well as dict-like lookup and iteration of the data attributes us-
ing [Link][u, v]['color'] and for e, datadict in [Link]():. Methods [Link].
items() and [Link]() are familiar from python dicts. In addition [Link]() provides
specific attribute iteration e.g. for e, e_color in [Link]('color'):.
The basic graph relationship of an edge can be obtained in two ways. One can look for neighbors of a node or one can
look for edges. We jokingly refer to people who focus on nodes/neighbors as node-centric and people who focus on
edges as edge-centric. The designers of NetworkX tend to be node-centric and view edges as a relationship between
nodes. You can see this by our choice of lookup notation like G[u] providing neighbors (adjacency) while edge
lookup is [Link][u, v]. Most data structures for sparse graphs are essentially adjacency lists and so fit this
perspective. In the end, of course, it doesn’t really matter which way you examine the graph. [Link] removes
duplicate representations of undirected edges while neighbor reporting across all nodes will naturally report both
directions.
Any properties that are more complicated than edges, neighbors and degree are provided by functions. For exam-
ple [Link](G, n) gives the number of triangles which include node n as a vertex. These functions are
grouped in the code and documentation under the term algorithms.
1.5 Algorithms
A number of graph algorithms are provided with NetworkX. These include shortest path, and breadth first search (see
traversal), clustering and isomorphism algorithms and others. There are many that we have not developed yet too. If
you implement a graph algorithm that might be useful for others please let us know through the NetworkX Google
group or the Github Developer Zone.
As an example here is code to use Dijkstra’s algorithm to find the shortest weighted path:
>>> G = [Link]()
>>> 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']
1.6 Drawing
While NetworkX is not designed as a network drawing tool, we provide a simple interface to drawing packages
and some simple layout algorithms. We interface to the excellent Graphviz layout tools like dot and neato with the
(suggested) pygraphviz package or the pydot interface. Drawing can be done using external programs or the Matplotlib
Python package. Interactive GUI interfaces are possible, though not provided. The drawing tools are provided in the
module drawing.
The basic drawing functions essentially place the nodes on a scatterplot using the positions you provide via a dictionary
or the positions are computed with a layout function. The edges are lines between those dots.
4 Chapter 1. Introduction
NetworkX Reference, Release 2.5
NetworkX uses a “dictionary of dictionaries of dictionaries” as the basic network data structure. This allows fast
lookup with reasonable storage for large sparse networks. The keys are nodes so G[u] returns an adjacency dictionary
keyed by neighbor to the edge attribute dictionary. A view of the adjacency data structure is provided by the dict-like
object [Link] as e.g. for node, nbrsdict in [Link]():. The expression G[u][v] returns the
edge attribute dictionary itself. A dictionary of lists would have also been possible, but not allow fast edge detection
nor convenient storage of edge data.
Advantages of dict-of-dicts-of-dicts data structure:
• Find edges and remove edges with two dictionary look-ups.
• Prefer to “lists” because of fast lookup with sparse storage.
• Prefer to “sets” since data can be attached to edge.
• G[u][v] returns the edge attribute dictionary.
• n in G tests if node n is in graph G.
• for n in G: iterates through the graph.
• for nbr in G[n]: iterates through neighbors.
As an example, here is a representation of an undirected graph with the edges (𝐴, 𝐵) and (𝐵, 𝐶).
>>> G = [Link]()
>>> G.add_edge('A', 'B')
>>> G.add_edge('B', 'C')
>>> print([Link])
{'A': {'B': {}}, 'B': {'A': {}, 'C': {}}, 'C': {'B': {}}}
The data structure gets morphed slightly for each base graph class. For DiGraph two dict-of-dicts-of-dicts structures
are provided, one for successors ([Link]) and one for predecessors ([Link]). For MultiGraph/MultiDiGraph
we use a dict-of-dicts-of-dicts-of-dicts1 where the third dictionary is keyed by an edge key identifier to the fourth
dictionary which contains the edge attributes for that edge between the two nodes.
Graphs provide two interfaces to the edge data attributes: adjacency and edges. So G[u][v]['width'] is the same
as [Link][u, v]['width'].
>>> G = [Link]()
>>> G.add_edge(1, 2, color='red', weight=0.84, size=300)
>>> print(G[1][2]['size'])
300
>>> print([Link][1, 2]['color'])
red
• ;
• ;
• .
6 Chapter 1. Introduction
CHAPTER
TWO
GRAPH TYPES
Overview
7
NetworkX Reference, Release 2.5
Examples
Create an empty graph structure (a “null graph”) with no nodes and no edges.
>>> G = [Link]()
>>> G.add_node(1)
Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).
In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a
customized node object, or even another Graph.
>>> G.add_node(H)
Edges:
G can also be grown by adding edges.
Add one edge,
>>> G.add_edge(1, 2)
a list of edges,
or a collection of edges,
>>> G.add_edges_from([Link])
If some edges connect nodes not yet in the graph, the nodes are added automatically. There are no errors when
adding nodes or edges that already exist.
Attributes:
Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys
must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct
manipulation of the attribute dictionaries named graph, node and edge respectively.
>>> G = [Link](day="Friday")
>>> [Link]
{'day': 'Friday'}
Warning: we protect the graph data structure by making [Link] a read-only dict-like structure. However, you
can assign to attributes in e.g. [Link][1, 2]. Thus, use 2 sets of brackets to add/change data attributes:
[Link][1, 2]['weight'] = 4 (For multigraphs: [Link][u, v, key][name] = value).
Shortcuts:
Many common graph features allow python syntax to speed reporting.
>>> 1 in G # check if node in graph
True
>>> [n for n in G if n < 3] # iterate through nodes
[1, 2]
>>> len(G) # number of nodes in graph
5
Often the best way to traverse all edges of a graph is via the neighbors. The neighbors are reported as an
adjacency-dict [Link] or [Link]()
>>> for n, nbrsdict in [Link]():
... for nbr, eattr in [Link]():
... if "weight" in eattr:
... # Do something useful with the edges
... pass
Reporting:
Simple graph information is obtained using object-attributes and methods. Reporting typically provides views
instead of containers to reduce memory usage. The views update as the graph is updated similarly to dict-
views. The objects nodes, edges and adj provide access to data attributes via lookup (e.g. nodes[n],
Examples
Create a low memory graph class that effectively disallows edge attributes by using a single attribute dict for all
edges. This reduces the memory used, but you lose edge attributes.
Please see ordered for more examples of creating graph subclasses by overwriting the base class dict with
a dictionary-like object.
Methods
[Link].__init__
Graph.__init__(incoming_graph_data=None, **attr)
Initialize a graph with edges, name, or graph attributes.
Parameters
• incoming_graph_data (input graph (optional, default: None)) – Data to initialize graph. If
None (default) an empty graph is created. The data can be an edge list, or any NetworkX
graph object. If the corresponding optional Python packages are installed the data can also
be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph.
• attr (keyword arguments, optional (default= no attributes)) – Attributes to add to graph as
key=value pairs.
See also:
convert()
Examples
[Link].add_node
Graph.add_node(node_for_adding, **attr)
Add a single node node_for_adding and update node attributes.
Parameters
• node_for_adding (node) – A node can be any hashable Python object except None.
• attr (keyword arguments, optional) – Set or change node attributes using key=value.
See also:
add_nodes_from()
Examples
Notes
A hashable object is one that can be used as a key in a Python dictionary. This includes strings, numbers, tuples
of strings and numbers, etc.
On many platforms hashable items also include mutables such as NetworkX Graphs, though one should be
careful that the hash doesn’t change on mutables.
[Link].add_nodes_from
Graph.add_nodes_from(nodes_for_adding, **attr)
Add multiple nodes.
Parameters
• nodes_for_adding (iterable container) – A container of nodes (list, dict, set, etc.). OR A
container of (node, attribute dict) tuples. Node attributes are updated using the attribute dict.
• attr (keyword arguments, optional (default= no attributes)) – Update attributes for all nodes
in nodes. Node attributes specified in nodes as a tuple take precedence over attributes spec-
ified via keyword arguments.
See also:
add_node()
Examples
[Link].remove_node
Graph.remove_node(n)
Remove node n.
Removes the node n and all adjacent edges. Attempting to remove a non-existent node will raise an exception.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
remove_nodes_from()
Examples
[Link].remove_nodes_from
Graph.remove_nodes_from(nodes)
Remove multiple nodes.
Parameters nodes (iterable container) – A container of nodes (list, dict, set, etc.). If a node in the
container is not in the graph it is silently ignored.
See also:
remove_node()
Examples
[Link].add_edge
Notes
Examples
>>> G.add_edge(1, 2)
>>> G[1][2].update({0: 5})
>>> [Link][1, 2].update({0: 5})
[Link].add_edges_from
Graph.add_edges_from(ebunch_to_add, **attr)
Add all the edges in ebunch_to_add.
Parameters
• ebunch_to_add (container of edges) – Each edge given in the container will be added to
the graph. The edges must be given as as 2-tuples (u, v) or 3-tuples (u, v, d) where d is a
dictionary containing edge data.
• attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using
keyword arguments.
See also:
Notes
Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments.
Examples
[Link].add_weighted_edges_from
Notes
Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph,
duplicate edges are stored.
Examples
[Link].remove_edge
Graph.remove_edge(u, v)
Remove the edge between u and v.
Parameters u, v (nodes) – Remove the edge between nodes u and v.
Raises NetworkXError – If there is not an edge between u and v.
See also:
Examples
[Link].remove_edges_from
Graph.remove_edges_from(ebunch)
Remove all edges specified in ebunch.
Parameters ebunch (list or container of edge tuples) – Each edge given in the list or container will
be removed from the graph. The edges can be:
• 2-tuples (u, v) edge between u and v.
• 3-tuples (u, v, k) where k is ignored.
See also:
Notes
Examples
[Link]
[Link](edges=None, nodes=None)
Update the graph using nodes/edges/graphs as input.
Like [Link], this method takes a graph as input, adding the graph’s nodes and edges to this graph. It can
also take two inputs: edges and nodes. Finally it can take either edges or nodes. To specify only nodes the
keyword nodes must be used.
The collections of edges and nodes are treated similarly to the add_edges_from/add_nodes_from methods.
When iterated, they should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
Parameters
• edges (Graph object, collection of edges, or None) – The first parameter can be a graph or
some edges. If it has attributes nodes and edges, then it is taken to be a Graph-like object
and those attributes are used as collections of nodes and edges to be added to the graph. If
the first parameter does not have those attributes, it is treated as a collection of edges and
added to the graph. If the first argument is None, no edges are added.
• nodes (collection of nodes, or None) – The second parameter is treated as a collection of
nodes to be added to the graph unless it is None. If edges is None and nodes is
None an exception is raised. If the first parameter is a Graph, then nodes is ignored.
Examples
>>> G = nx.path_graph(5)
>>> [Link](nx.complete_graph(range(4, 10)))
>>> from itertools import combinations
>>> edges = (
... (u, v, {"power": u * v})
... for u, v in combinations(range(10, 20), 2)
... if u * v < 225
... )
>>> nodes = [1000] # for singleton, use a container
>>> [Link](edges, nodes)
Notes
It you want to update the graph using an adjacency structure it is straightforward to obtain the edges/nodes from
adjacency. The following examples provide common cases, your adjacency may be slightly different and require
tweaks of these examples.
>>> # dict-of-set/list/tuple
>>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
>>> e = [(u, v) for u, nbrs in [Link]() for v in nbrs]
>>> [Link](edges=e, nodes=adj)
>>> DG = [Link]()
>>> # dict-of-dict-of-attribute
>>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
>>> e = [
... (u, v, {"weight": d})
... for u, nbrs in [Link]()
... for v, d in [Link]()
... ]
>>> [Link](edges=e, nodes=adj)
>>> # dict-of-dict-of-dict
>>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
>>> e = [
... (u, v, {"weight": d})
... for u, nbrs in [Link]()
... for v, d in [Link]()
... ]
>>> [Link](edges=e, nodes=adj)
See also:
[Link]
[Link]()
Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
Examples
[Link].clear_edges
Graph.clear_edges()
Remove all edges from the graph without altering nodes.
Examples
[Link]
property [Link]
A NodeView of the Graph as [Link] or [Link]().
Can be used as [Link] for data lookup and for set-like operations. Can also be used as G.
nodes(data='color', default=None) to return a NodeDataView which reports specific node data
but no set operations. It presents a dict-like interface as well with [Link]() iterating over (node,
nodedata) 2-tuples and [Link][3]['foo'] providing the value of the foo attribute for node 3. In
addition, a view [Link]('foo') provides a dict-like interface to the foo attribute of each node.
[Link]('foo', default=1) provides a default for nodes that do not have attribute foo.
Parameters
• data (string or bool, optional (default=False)) – The node attribute returned in 2-tuple (n,
ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the
nodes n.
• default (value, optional (default=None)) – Value used for nodes that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns
Allows set-like operations over the nodes as well as node attribute dict lookup and calling to
get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A
NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node,
attribute value) where the attribute is specified in data. If data is True then the attribute becomes
the entire data dictionary.
Return type NodeView
Notes
If your node data is not needed, it is simpler and equivalent to use the expression for n in G, or list(G).
Examples
There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3)
>>> list([Link])
[0, 1, 2]
>>> list(G)
[0, 1, 2]
>>> list([Link](data="foo"))
[(0, 'bar'), (1, None), (2, None)]
>>> list([Link]("foo"))
[(0, 'bar'), (1, None), (2, None)]
>>> list([Link](data="time"))
[(0, None), (1, '5pm'), (2, None)]
>>> list([Link]("time"))
[(0, None), (1, '5pm'), (2, None)]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create
a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never
None:
>>> G = [Link]()
>>> G.add_node(0)
>>> G.add_node(1, weight=2)
>>> G.add_node(2, weight=3)
>>> dict([Link](data="weight", default=1))
{0: 1, 1: 2, 2: 3}
[Link].__iter__
Graph.__iter__()
Iterate over the nodes. Use: ‘for n in G’.
Returns niter – An iterator over all nodes in the graph.
Return type iterator
Examples
[Link].has_node
Graph.has_node(n)
Returns True if the graph contains the node n.
Identical to n in G
Parameters n (node)
Examples
>>> 0 in G
True
[Link].__contains__
Graph.__contains__(n)
Returns True if n is a node, False otherwise. Use: ‘n in G’.
Examples
[Link]
property [Link]
An EdgeView of the Graph as [Link] or [Link]().
edges(self, nbunch=None, data=False, default=None)
The EdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called,
it also provides an EdgeDataView object which allows control of access to edge attributes (but does not pro-
vide set-like operations). Hence, [Link][u, v]['color'] provides the value of the color attribute for
edge (u, v) while for (u, v, c) in [Link]('color', default='red'): iterates
through all the edges yielding the color attribute with default 'red' if no color attribute exists.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges,
but can also be used for attribute lookup as edges[u, v]['foo'].
Return type EdgeView
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
[Link].has_edge
Graph.has_edge(u, v)
Returns True if the edge (u, v) is in the graph.
This is the same as v in G[u] without KeyError exceptions.
Parameters u, v (nodes) – Nodes can be, for example, strings or numbers. Nodes must be hashable
(and not None) Python objects.
Returns edge_ind – True if edge is in the graph, False otherwise.
Return type bool
Examples
>>> G.has_edge(0, 1)
True
>>> 1 in G[0] # though this gives KeyError if 0 not in G
True
[Link].get_edge_data
Graph.get_edge_data(u, v, default=None)
Returns the attribute dictionary associated with edge (u, v).
This is identical to G[u][v] except the default is returned instead of an exception if the edge doesn’t exist.
Parameters
• u, v (nodes)
• default (any Python object (default=None)) – Value to return if the edge (u, v) is not found.
Returns edge_dict – The edge attribute dictionary.
Return type dictionary
Examples
Warning: Assigning to G[u][v] is not permitted. But it is safe to assign attributes G[u][v]['foo']
>>> G[0][1]["weight"] = 7
>>> G[0][1]["weight"]
7
>>> G[1][0]["weight"]
7
[Link]
[Link](n)
Returns an iterator over all neighbors of node n.
This is identical to iter(G[n])
Parameters n (node) – A node in the graph
Returns neighbors – An iterator over all neighbors of node n
Return type iterator
Raises NetworkXError – If the node n is not in the graph.
Examples
Notes
[Link]
property [Link]
Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed
by neighbor to the edge-data-dict. So [Link][3][2]['color'] = 'blue' sets the color of the edge (3,
2) to "blue".
Iterating over [Link] behaves like a dict. Useful idioms include for nbr, datadict in [Link][n].
items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, [Link] holds outgoing (successor) info.
[Link].__getitem__
Graph.__getitem__(n)
Returns a dict of neighbors of node n. Use: ‘G[n]’.
Parameters n (node) – A node in the graph.
Returns adj_dict – The adjacency dictionary for nodes connected to n.
Return type dictionary
Notes
G[n] is the same as [Link][n] and similar to [Link](n) (which is an iterator over [Link][n])
Examples
[Link]
[Link]()
Returns an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
Returns adj_iter – An iterator over (node, adjacency dictionary) for all nodes in the graph.
Return type iterator
Examples
[Link].nbunch_iter
Graph.nbunch_iter(nbunch=None)
Returns an iterator over nodes contained in nbunch that are also in the graph.
The nodes in nbunch are checked for membership in the graph and if not are silently ignored.
Parameters nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
Returns niter – An iterator over nodes in nbunch that are also in the graph. If nbunch is None,
iterate over all nodes in the graph.
Return type iterator
Notes
When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when
nbunch is exhausted.
To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a NetworkXError is raised. Also, if
any object in nbunch is not hashable, a NetworkXError is raised.
[Link]
[Link]()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), __len__()
Examples
[Link].number_of_nodes
Graph.number_of_nodes()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
order(), __len__()
Examples
[Link].__len__
Graph.__len__()
Returns the number of nodes in the graph. Use: ‘len(G)’.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), order()
Examples
[Link]
property [Link]
A DegreeView for the Graph as [Link] or [Link]().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge
weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an edge attribute that holds
the numerical value used as a weight. If None, then each edge has weight 1. The degree is
the sum of the edge weights adjacent to the node.
Returns
• If a single node is requested
• deg (int) – Degree of the node
• OR if multiple nodes are requested
• nd_view (A DegreeView object capable of iterating (node, degree) pairs)
Examples
[Link]
[Link](weight=None)
Returns the number of edges or total of all edge weights.
Parameters weight (string or None, optional (default=None)) – The edge attribute that holds the
numerical value used as a weight. If None, then each edge has weight 1.
Returns
size – The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are
more general).
Return type numeric
See also:
number_of_edges()
Examples
[Link].number_of_edges
Graph.number_of_edges(u=None, v=None)
Returns the number of edges between two nodes.
Parameters u, v (nodes, optional (default=all edges)) – If u and v are specified, return the number
of edges between u and v. Otherwise return the total number of all edges.
Returns nedges – The number of edges in the graph. If nodes u and v are specified return the
number of edges between those nodes. If the graph is directed, this only returns the number of
edges from u to v.
Return type int
See also:
size()
Examples
For undirected graphs, this method counts the total number of edges in the graph:
>>> G = nx.path_graph(4)
>>> G.number_of_edges()
3
If you specify two nodes, this counts the total number of edges joining the two nodes:
>>> G.number_of_edges(0, 1)
1
For directed graphs, this method can count the total number of directed edges from u to v:
>>> G = [Link]()
>>> G.add_edge(0, 1)
>>> G.add_edge(1, 0)
>>> G.number_of_edges(0, 1)
1
[Link]
[Link](as_view=False)
Returns a copy of the graph.
The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an
attribute is a container, that container is shared by the original an the copy. Use Python’s [Link] for
new containers.
If as_view is True then a view is returned instead of a copy.
Notes
All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four
types of copies of a graph that people might want.
Deepcopy – A “deepcopy” copies the graph structure as well as all data attributes and any objects they might
contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s
[Link])
Data Reference (Shallow) – For a shallow copy the graph structure is copied but the edge, node and graph at-
tribute dicts are references to those in the original graph. This saves time and memory but could cause confusion
if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this
level of shallow copy.
Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the
attributes. That is, any attributes that are containers are shared between the new graph and the original. This is
exactly what [Link]() provides. You can obtain this style copy using:
>>> G = nx.path_graph(5)
>>> H = [Link]()
>>> H = [Link](as_view=False)
>>> H = [Link](G)
>>> H = G.__class__(G)
Fresh Data – For fresh data, the graph structure is copied while new empty data attribute dicts are created. The
resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not
enabled. Instead use:
>>> H = G.__class__()
>>> H.add_nodes_from(G)
>>> H.add_edges_from([Link])
View – Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy
of the original structure without requiring any memory for copying the information.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Parameters as_view (bool, optional (default=False)) – If True, the returned graph-view provides a
read-only view of the original graph without actually copying any data.
Returns G – A copy of the graph.
Return type Graph
See also:
Examples
[Link].to_undirected
Graph.to_undirected(as_view=False)
Returns an undirected copy of the graph.
Parameters as_view (bool (optional, default=False)) – If True return a view of the original undi-
rected graph.
Returns G – A deepcopy of the graph.
Return type Graph/MultiGraph
See also:
Graph(), copy(), add_edge(), add_edges_from()
Notes
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar G = [Link](D) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Warning: If you have subclassed DiGraph to use dict-like objects in the data structure, those changes do not
transfer to the Graph created by this method.
Examples
[Link].to_directed
Graph.to_directed(as_view=False)
Returns a directed representation of the graph.
Returns G – A directed graph with the same name, same nodes, and with each edge (u, v, data)
replaced by two directed edges (u, v, data) and (v, u, data).
Return type DiGraph
Notes
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Warning: If you have subclassed Graph to use dict-like objects in the data structure, those changes do not
transfer to the DiGraph created by this method.
Examples
[Link]
[Link](nodes)
Returns a SubGraph view of the subgraph induced on nodes.
The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.
Parameters nodes (list, iterable) – A container of nodes which will be iterated through once.
Returns G – A subgraph view of the graph. The graph structure cannot be changed but node/edge
attributes can and are shared with the original graph.
Return type SubGraph View
Notes
The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled
out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: [Link](nodes).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([n for n in G
if n not in set(nodes)])
Subgraph views are sometimes NOT what you want. In most cases where you want to do more than simply look
at the induced edges, it makes more sense to just create the subgraph as its own graph with code like:
Examples
[Link].edge_subgraph
Graph.edge_subgraph(edges)
Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any one of those edges.
Parameters edges (iterable) – An iterable of edges in this graph.
Returns G – An edge-induced subgraph of this graph with the same edge attributes.
Return type Graph
Notes
The graph, edge, and node attributes in the returned subgraph view are references to the corresponding attributes
in the original graph. The view is read-only.
To create a full graph version of the subgraph with its own copy of the edge or node attributes, use:
>>> G.edge_subgraph(edges).copy()
Examples
>>> G = nx.path_graph(5)
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
>>> list([Link])
[0, 1, 3, 4]
>>> list([Link])
[(0, 1), (3, 4)]
Overview
See also:
Graph, MultiGraph, MultiDiGraph, OrderedDiGraph
Examples
Create an empty graph structure (a “null graph”) with no nodes and no edges.
>>> G = [Link]()
>>> G.add_node(1)
Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).
In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a
customized node object, or even another Graph.
>>> G.add_node(H)
Edges:
G can also be grown by adding edges.
Add one edge,
>>> G.add_edge(1, 2)
a list of edges,
or a collection of edges,
>>> G.add_edges_from([Link])
If some edges connect nodes not yet in the graph, the nodes are added automatically. There are no errors when
adding nodes or edges that already exist.
Attributes:
Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys
must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct
manipulation of the attribute dictionaries named graph, node and edge respectively.
>>> G = [Link](day="Friday")
>>> [Link]
{'day': 'Friday'}
Warning: we protect the graph data structure by making [Link][1, 2] a read-only dict-like structure.
However, you can assign to attributes in e.g. [Link][1, 2]. Thus, use 2 sets of brackets to add/change data
attributes: [Link][1, 2]['weight'] = 4 (For multigraphs: [Link][u, v, key][name] =
value).
Shortcuts:
Many common graph features allow python syntax to speed reporting.
Often the best way to traverse all edges of a graph is via the neighbors. The neighbors are reported as an
adjacency-dict [Link] or [Link]()
Reporting:
Simple graph information is obtained using object-attributes and methods. Reporting usually provides
views instead of containers to reduce memory usage. The views update as the graph is updated simi-
larly to dict-views. The objects nodes, `edges and adj provide access to data attributes via lookup
(e.g. nodes[n], `edges[u, v], adj[u][v]) and iteration (e.g. [Link](), nodes.
data('color'), [Link]('color', default='blue') and similarly for edges) Views exist
for nodes, edges, neighbors()/adj and degree.
Examples
Create a low memory graph class that effectively disallows edge attributes by using a single attribute dict for all
edges. This reduces the memory used, but you lose edge attributes.
Please see ordered for more examples of creating graph subclasses by overwriting the base class dict with
a dictionary-like object.
Methods
[Link].__init__
DiGraph.__init__(incoming_graph_data=None, **attr)
Initialize a graph with edges, name, or graph attributes.
Parameters
• incoming_graph_data (input graph (optional, default: None)) – Data to initialize graph. If
None (default) an empty graph is created. The data can be an edge list, or any NetworkX
graph object. If the corresponding optional Python packages are installed the data can also
be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph.
• attr (keyword arguments, optional (default= no attributes)) – Attributes to add to graph as
key=value pairs.
See also:
convert()
Examples
[Link].add_node
DiGraph.add_node(node_for_adding, **attr)
Add a single node node_for_adding and update node attributes.
Parameters
• node_for_adding (node) – A node can be any hashable Python object except None.
• attr (keyword arguments, optional) – Set or change node attributes using key=value.
See also:
add_nodes_from()
Examples
Notes
A hashable object is one that can be used as a key in a Python dictionary. This includes strings, numbers, tuples
of strings and numbers, etc.
On many platforms hashable items also include mutables such as NetworkX Graphs, though one should be
careful that the hash doesn’t change on mutables.
[Link].add_nodes_from
DiGraph.add_nodes_from(nodes_for_adding, **attr)
Add multiple nodes.
Parameters
• nodes_for_adding (iterable container) – A container of nodes (list, dict, set, etc.). OR A
container of (node, attribute dict) tuples. Node attributes are updated using the attribute dict.
• attr (keyword arguments, optional (default= no attributes)) – Update attributes for all nodes
in nodes. Node attributes specified in nodes as a tuple take precedence over attributes spec-
ified via keyword arguments.
See also:
add_node()
Examples
[Link].remove_node
DiGraph.remove_node(n)
Remove node n.
Removes the node n and all adjacent edges. Attempting to remove a non-existent node will raise an exception.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
remove_nodes_from()
Examples
[Link].remove_nodes_from
DiGraph.remove_nodes_from(nodes)
Remove multiple nodes.
Parameters nodes (iterable container) – A container of nodes (list, dict, set, etc.). If a node in the
container is not in the graph it is silently ignored.
See also:
remove_node()
Examples
[Link].add_edge
Notes
Examples
>>> G.add_edge(1, 2)
>>> G[1][2].update({0: 5})
>>> [Link][1, 2].update({0: 5})
[Link].add_edges_from
DiGraph.add_edges_from(ebunch_to_add, **attr)
Add all the edges in ebunch_to_add.
Parameters
• ebunch_to_add (container of edges) – Each edge given in the container will be added to the
graph. The edges must be given as 2-tuples (u, v) or 3-tuples (u, v, d) where d is a dictionary
containing edge data.
• attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using
keyword arguments.
See also:
Notes
Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments.
Examples
[Link].add_weighted_edges_from
Notes
Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph,
duplicate edges are stored.
Examples
[Link].remove_edge
DiGraph.remove_edge(u, v)
Remove the edge between u and v.
Parameters u, v (nodes) – Remove the edge between nodes u and v.
Raises NetworkXError – If there is not an edge between u and v.
See also:
Examples
[Link].remove_edges_from
DiGraph.remove_edges_from(ebunch)
Remove all edges specified in ebunch.
Parameters ebunch (list or container of edge tuples) – Each edge given in the list or container will
be removed from the graph. The edges can be:
• 2-tuples (u, v) edge between u and v.
• 3-tuples (u, v, k) where k is ignored.
See also:
Notes
Examples
[Link]
[Link](edges=None, nodes=None)
Update the graph using nodes/edges/graphs as input.
Like [Link], this method takes a graph as input, adding the graph’s nodes and edges to this graph. It can
also take two inputs: edges and nodes. Finally it can take either edges or nodes. To specify only nodes the
keyword nodes must be used.
The collections of edges and nodes are treated similarly to the add_edges_from/add_nodes_from methods.
When iterated, they should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
Parameters
• edges (Graph object, collection of edges, or None) – The first parameter can be a graph or
some edges. If it has attributes nodes and edges, then it is taken to be a Graph-like object
and those attributes are used as collections of nodes and edges to be added to the graph. If
the first parameter does not have those attributes, it is treated as a collection of edges and
added to the graph. If the first argument is None, no edges are added.
• nodes (collection of nodes, or None) – The second parameter is treated as a collection of
nodes to be added to the graph unless it is None. If edges is None and nodes is
None an exception is raised. If the first parameter is a Graph, then nodes is ignored.
Examples
>>> G = nx.path_graph(5)
>>> [Link](nx.complete_graph(range(4, 10)))
>>> from itertools import combinations
>>> edges = (
... (u, v, {"power": u * v})
... for u, v in combinations(range(10, 20), 2)
... if u * v < 225
... )
>>> nodes = [1000] # for singleton, use a container
>>> [Link](edges, nodes)
Notes
It you want to update the graph using an adjacency structure it is straightforward to obtain the edges/nodes from
adjacency. The following examples provide common cases, your adjacency may be slightly different and require
tweaks of these examples.
>>> # dict-of-set/list/tuple
>>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
>>> e = [(u, v) for u, nbrs in [Link]() for v in nbrs]
>>> [Link](edges=e, nodes=adj)
>>> DG = [Link]()
>>> # dict-of-dict-of-attribute
>>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
>>> e = [
... (u, v, {"weight": d})
... for u, nbrs in [Link]()
... for v, d in [Link]()
... ]
>>> [Link](edges=e, nodes=adj)
>>> # dict-of-dict-of-dict
>>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
>>> e = [
... (u, v, {"weight": d})
... for u, nbrs in [Link]()
... for v, d in [Link]()
... ]
>>> [Link](edges=e, nodes=adj)
See also:
[Link]
[Link]()
Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
Examples
[Link].clear_edges
DiGraph.clear_edges()
Remove all edges from the graph without altering nodes.
Examples
[Link]
property [Link]
A NodeView of the Graph as [Link] or [Link]().
Can be used as [Link] for data lookup and for set-like operations. Can also be used as G.
nodes(data='color', default=None) to return a NodeDataView which reports specific node data
but no set operations. It presents a dict-like interface as well with [Link]() iterating over (node,
nodedata) 2-tuples and [Link][3]['foo'] providing the value of the foo attribute for node 3. In
addition, a view [Link]('foo') provides a dict-like interface to the foo attribute of each node.
[Link]('foo', default=1) provides a default for nodes that do not have attribute foo.
Parameters
• data (string or bool, optional (default=False)) – The node attribute returned in 2-tuple (n,
ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the
nodes n.
• default (value, optional (default=None)) – Value used for nodes that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns
Allows set-like operations over the nodes as well as node attribute dict lookup and calling to
get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A
NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node,
attribute value) where the attribute is specified in data. If data is True then the attribute becomes
the entire data dictionary.
Return type NodeView
Notes
If your node data is not needed, it is simpler and equivalent to use the expression for n in G, or list(G).
Examples
There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3)
>>> list([Link])
[0, 1, 2]
>>> list(G)
[0, 1, 2]
>>> list([Link](data="foo"))
[(0, 'bar'), (1, None), (2, None)]
>>> list([Link]("foo"))
[(0, 'bar'), (1, None), (2, None)]
>>> list([Link](data="time"))
[(0, None), (1, '5pm'), (2, None)]
>>> list([Link]("time"))
[(0, None), (1, '5pm'), (2, None)]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create
a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never
None:
>>> G = [Link]()
>>> G.add_node(0)
>>> G.add_node(1, weight=2)
>>> G.add_node(2, weight=3)
>>> dict([Link](data="weight", default=1))
{0: 1, 1: 2, 2: 3}
[Link].__iter__
DiGraph.__iter__()
Iterate over the nodes. Use: ‘for n in G’.
Returns niter – An iterator over all nodes in the graph.
Return type iterator
Examples
[Link].has_node
DiGraph.has_node(n)
Returns True if the graph contains the node n.
Identical to n in G
Parameters n (node)
Examples
>>> 0 in G
True
[Link].__contains__
DiGraph.__contains__(n)
Returns True if n is a node, False otherwise. Use: ‘n in G’.
Examples
[Link]
property [Link]
An OutEdgeView of the DiGraph as [Link] or [Link]().
edges(self, nbunch=None, data=False, default=None)
The OutEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called,
it also provides an EdgeDataView object which allows control of access to edge attributes (but does not pro-
vide set-like operations). Hence, [Link][u, v]['color'] provides the value of the color attribute for
edge (u, v) while for (u, v, c) in [Link]('color', default='red'): iterates
through all the edges yielding the color attribute with default 'red' if no color attribute exists.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges,
but can also be used for attribute lookup as edges[u, v]['foo'].
Return type OutEdgeView
See also:
in_edges, out_edges
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
[Link].out_edges
property DiGraph.out_edges
An OutEdgeView of the DiGraph as [Link] or [Link]().
edges(self, nbunch=None, data=False, default=None)
The OutEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called,
it also provides an EdgeDataView object which allows control of access to edge attributes (but does not pro-
vide set-like operations). Hence, [Link][u, v]['color'] provides the value of the color attribute for
edge (u, v) while for (u, v, c) in [Link]('color', default='red'): iterates
through all the edges yielding the color attribute with default 'red' if no color attribute exists.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges,
but can also be used for attribute lookup as edges[u, v]['foo'].
Return type OutEdgeView
See also:
in_edges, out_edges
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
[Link].in_edges
property DiGraph.in_edges
An InEdgeView of the Graph as G.in_edges or G.in_edges().
in_edges(self, nbunch=None, data=False, default=None):
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns in_edges – A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of
edges, but can also be used for attribute lookup as edges[u, v]['foo'].
Return type InEdgeView
See also:
edges
[Link].has_edge
DiGraph.has_edge(u, v)
Returns True if the edge (u, v) is in the graph.
This is the same as v in G[u] without KeyError exceptions.
Parameters u, v (nodes) – Nodes can be, for example, strings or numbers. Nodes must be hashable
(and not None) Python objects.
Returns edge_ind – True if edge is in the graph, False otherwise.
Return type bool
Examples
>>> G.has_edge(0, 1)
True
>>> 1 in G[0] # though this gives KeyError if 0 not in G
True
[Link].get_edge_data
DiGraph.get_edge_data(u, v, default=None)
Returns the attribute dictionary associated with edge (u, v).
This is identical to G[u][v] except the default is returned instead of an exception if the edge doesn’t exist.
Parameters
• u, v (nodes)
• default (any Python object (default=None)) – Value to return if the edge (u, v) is not found.
Returns edge_dict – The edge attribute dictionary.
Return type dictionary
Examples
Warning: Assigning to G[u][v] is not permitted. But it is safe to assign attributes G[u][v]['foo']
>>> G[0][1]["weight"] = 7
>>> G[0][1]["weight"]
7
>>> G[1][0]["weight"]
7
[Link]
[Link](n)
Returns an iterator over successor nodes of n.
A successor of n is a node m such that there exists a directed edge from n to m.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
predecessors()
Notes
[Link]
property [Link]
Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed
by neighbor to the edge-data-dict. So [Link][3][2]['color'] = 'blue' sets the color of the edge (3,
2) to "blue".
Iterating over [Link] behaves like a dict. Useful idioms include for nbr, datadict in [Link][n].
items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, [Link] holds outgoing (successor) info.
[Link].__getitem__
DiGraph.__getitem__(n)
Returns a dict of neighbors of node n. Use: ‘G[n]’.
Parameters n (node) – A node in the graph.
Returns adj_dict – The adjacency dictionary for nodes connected to n.
Return type dictionary
Notes
G[n] is the same as [Link][n] and similar to [Link](n) (which is an iterator over [Link][n])
Examples
[Link]
[Link](n)
Returns an iterator over successor nodes of n.
A successor of n is a node m such that there exists a directed edge from n to m.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
predecessors()
Notes
[Link]
property [Link]
Graph adjacency object holding the successors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is
keyed by neighbor to the edge-data-dict. So [Link][3][2]['color'] = 'blue' sets the color of the
edge (3, 2) to "blue".
Iterating over [Link] behaves like a dict. Useful idioms include for nbr, datadict in [Link][n].
items():. A data-view not provided by dicts also exists: for nbr, foovalue in [Link][node].
data('foo'): and a default can be set via a default argument to the data method.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, [Link] is identical to [Link].
[Link]
[Link](n)
Returns an iterator over predecessor nodes of n.
A predecessor of n is a node m such that there exists a directed edge from m to n.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
successors()
[Link]
property [Link]
Graph adjacency object holding the predecessors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is
keyed by neighbor to the edge-data-dict. So [Link][2][3]['color'] = 'blue' sets the color of the
edge (3, 2) to "blue".
Iterating over [Link] behaves like a dict. Useful idioms include for nbr, datadict in [Link][n].
items():. A data-view not provided by dicts also exists: for nbr, foovalue in [Link][node].
data('foo'): A default can be set via a default argument to the data method.
[Link]
[Link]()
Returns an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
Returns adj_iter – An iterator over (node, adjacency dictionary) for all nodes in the graph.
Return type iterator
Examples
[Link].nbunch_iter
DiGraph.nbunch_iter(nbunch=None)
Returns an iterator over nodes contained in nbunch that are also in the graph.
The nodes in nbunch are checked for membership in the graph and if not are silently ignored.
Parameters nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
Returns niter – An iterator over nodes in nbunch that are also in the graph. If nbunch is None,
iterate over all nodes in the graph.
Return type iterator
Raises NetworkXError – If nbunch is not a node or or sequence of nodes. If a node in nbunch is
not hashable.
See also:
Graph.__iter__()
Notes
When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when
nbunch is exhausted.
To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a NetworkXError is raised. Also, if
any object in nbunch is not hashable, a NetworkXError is raised.
[Link]
[Link]()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), __len__()
Examples
[Link].number_of_nodes
DiGraph.number_of_nodes()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
order(), __len__()
Examples
[Link].__len__
DiGraph.__len__()
Returns the number of nodes in the graph. Use: ‘len(G)’.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), order()
Examples
[Link]
property [Link]
A DegreeView for the Graph as [Link] or [Link]().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge
weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an edge attribute that holds
the numerical value used as a weight. If None, then each edge has weight 1. The degree is
the sum of the edge weights adjacent to the node.
Returns
• If a single node is requested
• deg (int) – Degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, degree).
See also:
in_degree, out_degree
Examples
[Link].in_degree
property DiGraph.in_degree
An InDegreeView for (node, in_degree) or in_degree for single node.
The node in_degree is the number of edges pointing to the node. The weighted node degree is the sum of the
edge weights for edges incident to that node.
This object provides an iteration over (node, in_degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an edge attribute that holds
the numerical value used as a weight. If None, then each edge has weight 1. The degree is
the sum of the edge weights adjacent to the node.
Returns
• If a single node is requested
• deg (int) – In-degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, in-degree).
See also:
degree, out_degree
Examples
>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.in_degree(0) # node 0 with degree 0
0
>>> list(G.in_degree([0, 1, 2]))
[(0, 0), (1, 1), (2, 1)]
[Link].out_degree
property DiGraph.out_degree
An OutDegreeView for (node, out_degree)
The node out_degree is the number of edges pointing out of the node. The weighted node degree is the sum of
the edge weights for edges incident to that node.
This object provides an iterator over (node, out_degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an edge attribute that holds
the numerical value used as a weight. If None, then each edge has weight 1. The degree is
the sum of the edge weights adjacent to the node.
Returns
• If a single node is requested
• deg (int) – Out-degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, out-degree).
See also:
degree, in_degree
Examples
>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.out_degree(0) # node 0 with degree 1
1
>>> list(G.out_degree([0, 1, 2]))
[(0, 1), (1, 1), (2, 1)]
[Link]
[Link](weight=None)
Returns the number of edges or total of all edge weights.
Parameters weight (string or None, optional (default=None)) – The edge attribute that holds the
numerical value used as a weight. If None, then each edge has weight 1.
Returns
size – The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are
more general).
Return type numeric
See also:
number_of_edges()
Examples
[Link].number_of_edges
DiGraph.number_of_edges(u=None, v=None)
Returns the number of edges between two nodes.
Parameters u, v (nodes, optional (default=all edges)) – If u and v are specified, return the number
of edges between u and v. Otherwise return the total number of all edges.
Returns nedges – The number of edges in the graph. If nodes u and v are specified return the
number of edges between those nodes. If the graph is directed, this only returns the number of
edges from u to v.
Examples
For undirected graphs, this method counts the total number of edges in the graph:
>>> G = nx.path_graph(4)
>>> G.number_of_edges()
3
If you specify two nodes, this counts the total number of edges joining the two nodes:
>>> G.number_of_edges(0, 1)
1
For directed graphs, this method can count the total number of directed edges from u to v:
>>> G = [Link]()
>>> G.add_edge(0, 1)
>>> G.add_edge(1, 0)
>>> G.number_of_edges(0, 1)
1
[Link]
[Link](as_view=False)
Returns a copy of the graph.
The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an
attribute is a container, that container is shared by the original an the copy. Use Python’s [Link] for
new containers.
If as_view is True then a view is returned instead of a copy.
Notes
All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four
types of copies of a graph that people might want.
Deepcopy – A “deepcopy” copies the graph structure as well as all data attributes and any objects they might
contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s
[Link])
Data Reference (Shallow) – For a shallow copy the graph structure is copied but the edge, node and graph at-
tribute dicts are references to those in the original graph. This saves time and memory but could cause confusion
if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this
level of shallow copy.
Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the
attributes. That is, any attributes that are containers are shared between the new graph and the original. This is
exactly what [Link]() provides. You can obtain this style copy using:
>>> G = nx.path_graph(5)
>>> H = [Link]()
>>> H = [Link](as_view=False)
>>> H = [Link](G)
>>> H = G.__class__(G)
Fresh Data – For fresh data, the graph structure is copied while new empty data attribute dicts are created. The
resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not
enabled. Instead use:
>>> H = G.__class__()
>>> H.add_nodes_from(G)
>>> H.add_edges_from([Link])
View – Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy
of the original structure without requiring any memory for copying the information.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Parameters as_view (bool, optional (default=False)) – If True, the returned graph-view provides a
read-only view of the original graph without actually copying any data.
Returns G – A copy of the graph.
Return type Graph
See also:
Examples
[Link].to_undirected
DiGraph.to_undirected(reciprocal=False, as_view=False)
Returns an undirected representation of the digraph.
Parameters
• reciprocal (bool (optional)) – If True only keep edges that appear in both directions in the
original digraph.
• as_view (bool (optional, default=False)) – If True return an undirected view of the original
directed graph.
Returns G – An undirected graph with the same name and nodes and with edge (u, v, data) if either
(u, v, data) or (v, u, data) is in the digraph. If both edges exist in digraph and their edge data is
different, only one edge is created with an arbitrary choice of which edge data to use. You must
check and correct for this manually if desired.
Return type Graph
See also:
Graph(), copy(), add_edge(), add_edges_from()
Notes
If edges in both directions (u, v) and (v, u) exist in the graph, attributes for the new undirected edge will be a
combination of the attributes of the directed edges. The edge data is updated in the (arbitrary) order that the
edges are encountered. For more customized control of the edge attributes use add_edge().
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar G=DiGraph(D) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Warning: If you have subclassed DiGraph to use dict-like objects in the data structure, those changes do not
transfer to the Graph created by this method.
Examples
[Link].to_directed
DiGraph.to_directed(as_view=False)
Returns a directed representation of the graph.
Returns G – A directed graph with the same name, same nodes, and with each edge (u, v, data)
replaced by two directed edges (u, v, data) and (v, u, data).
Return type DiGraph
Notes
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Warning: If you have subclassed Graph to use dict-like objects in the data structure, those changes do not
transfer to the DiGraph created by this method.
Examples
[Link]
[Link](nodes)
Returns a SubGraph view of the subgraph induced on nodes.
The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.
Parameters nodes (list, iterable) – A container of nodes which will be iterated through once.
Returns G – A subgraph view of the graph. The graph structure cannot be changed but node/edge
attributes can and are shared with the original graph.
Return type SubGraph View
Notes
The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled
out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: [Link](nodes).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([n for n in G
if n not in set(nodes)])
Subgraph views are sometimes NOT what you want. In most cases where you want to do more than simply look
at the induced edges, it makes more sense to just create the subgraph as its own graph with code like:
Examples
[Link].edge_subgraph
DiGraph.edge_subgraph(edges)
Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any one of those edges.
Parameters edges (iterable) – An iterable of edges in this graph.
Returns G – An edge-induced subgraph of this graph with the same edge attributes.
Return type Graph
Notes
The graph, edge, and node attributes in the returned subgraph view are references to the corresponding attributes
in the original graph. The view is read-only.
To create a full graph version of the subgraph with its own copy of the edge or node attributes, use:
>>> G.edge_subgraph(edges).copy()
Examples
>>> G = nx.path_graph(5)
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
>>> list([Link])
[0, 1, 3, 4]
>>> list([Link])
[(0, 1), (3, 4)]
[Link]
[Link](copy=True)
Returns the reverse of the graph.
The reverse is a graph with the same nodes and edges but with the directions of the edges reversed.
Parameters copy (bool optional (default=True)) – If True, return a new DiGraph holding the re-
versed edges. If False, the reverse graph is created using a view of the original graph.
Overview
Examples
Create an empty graph structure (a “null graph”) with no nodes and no edges.
>>> G = [Link]()
>>> G.add_node(1)
Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).
In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a
customized node object, or even another Graph.
>>> G.add_node(H)
Edges:
G can also be grown by adding edges.
Add one edge,
a list of edges,
or a collection of edges,
If some edges connect nodes not yet in the graph, the nodes are added automatically. If an edge already exists,
an additional edge is created and stored using a key to identify the edge. By default the key is the lowest unused
integer.
Attributes:
Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys
must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct
manipulation of the attribute dictionaries named graph, node and edge respectively.
>>> G = [Link](day="Friday")
>>> [Link]
{'day': 'Friday'}
Warning: we protect the graph data structure by making [Link][1, 2] a read-only dict-like structure.
However, you can assign to attributes in e.g. [Link][1, 2]. Thus, use 2 sets of brackets to add/change data
attributes: [Link][1, 2]['weight'] = 4 (For multigraphs: [Link][u, v, key][name] =
value).
Shortcuts:
Many common graph features allow python syntax to speed reporting.
Often the best way to traverse all edges of a graph is via the neighbors. The neighbors are reported as an
adjacency-dict [Link] or [Link]().
Reporting:
Simple graph information is obtained using methods and object-attributes. Reporting usually provides
views instead of containers to reduce memory usage. The views update as the graph is updated simi-
larly to dict-views. The objects nodes, `edges and adj provide access to data attributes via lookup
(e.g. nodes[n], `edges[u, v], adj[u][v]) and iteration (e.g. [Link](), nodes.
data('color'), [Link]('color', default='blue') and similarly for edges) Views exist
for nodes, edges, neighbors()/adj and degree.
For details on these and other miscellaneous methods, see below.
Subclasses (Advanced):
The MultiGraph class uses a dict-of-dict-of-dict-of-dict data structure. The outer dict (node_dict) holds adja-
cency information keyed by node. The next dict (adjlist_dict) represents the adjacency information and holds
edge_key dicts keyed by neighbor. The edge_key dict holds each edge_attr dict keyed by edge key. The inner
dict (edge_attr_dict) represents the edge data and holds edge attribute values keyed by attribute names.
Each of these four dicts in the dict-of-dict-of-dict-of-dict structure can be replaced by a user defined dict-like
object. In general, the dict-like features should be maintained but extra features can be added. To replace
one of the dicts create a new graph class by changing the class(!) variable holding the factory for that dict-
like structure. The variable names are node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory and graph_attr_dict_factory.
node_dict_factory [function, (default: dict)] Factory function to be used to create the dict containing node
attributes, keyed by node id. It should require no arguments and return a dict-like object
node_attr_dict_factory: function, (default: dict) Factory function to be used to create the node attribute dict
which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like
object
adjlist_outer_dict_factory [function, (default: dict)] Factory function to be used to create the outer-most dict
in the data structure that holds adjacency info keyed by node. It should require no arguments and return a
dict-like object.
adjlist_inner_dict_factory [function, (default: dict)] Factory function to be used to create the adjacency list
dict which holds multiedge key dicts keyed by neighbor. It should require no arguments and return a
dict-like object.
edge_key_dict_factory [function, (default: dict)] Factory function to be used to create the edge key dict which
holds edge data keyed by edge key. It should require no arguments and return a dict-like object.
edge_attr_dict_factory [function, (default: dict)] Factory function to be used to create the edge attribute dict
which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like
object.
graph_attr_dict_factory [function, (default: dict)] Factory function to be used to create the graph attribute
dict which holds attribute values keyed by attribute name. It should require no arguments and return a
dict-like object.
Typically, if your extension doesn’t impact the data structure all methods will inherited without issue except:
to_directed/to_undirected. By default these methods create a DiGraph/Graph class and you probably
want them to create your extension of a DiGraph/Graph. To facilitate this we define two class variables that you
can set in your subclass.
to_directed_class [callable, (default: DiGraph or MultiDiGraph)] Class to create a new graph structure in the
to_directed method. If None, a NetworkX class (DiGraph or MultiDiGraph) is used.
to_undirected_class [callable, (default: Graph or MultiGraph)] Class to create a new graph structure in the
to_undirected method. If None, a NetworkX class (Graph or MultiGraph) is used.
Examples
Please see ordered for examples of creating graph subclasses by overwriting the base class dict with a
dictionary-like object.
Methods
[Link].__init__
MultiGraph.__init__(incoming_graph_data=None, **attr)
Initialize a graph with edges, name, or graph attributes.
Parameters
• incoming_graph_data (input graph) – Data to initialize graph. If incom-
ing_graph_data=None (default) an empty graph is created. The data can be an edge list,
or any NetworkX graph object. If the corresponding optional Python packages are installed
the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz
graph.
• attr (keyword arguments, optional (default= no attributes)) – Attributes to add to graph as
key=value pairs.
See also:
convert()
Examples
[Link].add_node
MultiGraph.add_node(node_for_adding, **attr)
Add a single node node_for_adding and update node attributes.
Parameters
• node_for_adding (node) – A node can be any hashable Python object except None.
• attr (keyword arguments, optional) – Set or change node attributes using key=value.
See also:
add_nodes_from()
Examples
Notes
A hashable object is one that can be used as a key in a Python dictionary. This includes strings, numbers, tuples
of strings and numbers, etc.
On many platforms hashable items also include mutables such as NetworkX Graphs, though one should be
careful that the hash doesn’t change on mutables.
[Link].add_nodes_from
MultiGraph.add_nodes_from(nodes_for_adding, **attr)
Add multiple nodes.
Parameters
• nodes_for_adding (iterable container) – A container of nodes (list, dict, set, etc.). OR A
container of (node, attribute dict) tuples. Node attributes are updated using the attribute dict.
• attr (keyword arguments, optional (default= no attributes)) – Update attributes for all nodes
in nodes. Node attributes specified in nodes as a tuple take precedence over attributes spec-
ified via keyword arguments.
See also:
add_node()
Examples
[Link].remove_node
MultiGraph.remove_node(n)
Remove node n.
Removes the node n and all adjacent edges. Attempting to remove a non-existent node will raise an exception.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
remove_nodes_from()
Examples
[Link].remove_nodes_from
MultiGraph.remove_nodes_from(nodes)
Remove multiple nodes.
Parameters nodes (iterable container) – A container of nodes (list, dict, set, etc.). If a node in the
container is not in the graph it is silently ignored.
See also:
remove_node()
Examples
[Link].add_edge
Notes
To replace/update edge data, use the optional key argument to identify a unique edge. Otherwise a new edge
will be created.
NetworkX algorithms designed for weighted graphs cannot use multigraphs directly because it is not clear
how to handle multiedge weights. Convert to Graph using edge attribute ‘weight’ to enable weighted graph
algorithms.
Default keys are generated using the method new_edge_key(). This method can be overridden by subclass-
ing the base class and providing a custom new_edge_key() method.
Examples
>>> G = [Link]()
>>> e = (1, 2)
>>> ekey = G.add_edge(1, 2) # explicit two-node form
>>> G.add_edge(*e) # single edge as tuple of two nodes
1
>>> G.add_edges_from([(1, 2)]) # add edges from iterable container
[2]
[Link].add_edges_from
MultiGraph.add_edges_from(ebunch_to_add, **attr)
Add all the edges in ebunch_to_add.
Parameters
• ebunch_to_add (container of edges) – Each edge given in the container will be added to
the graph. The edges can be:
– 2-tuples (u, v) or
– 3-tuples (u, v, d) for an edge data dict d, or
– 3-tuples (u, v, k) for not iterable key k, or
– 4-tuples (u, v, k, d) for an edge with data and key k
• attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using
keyword arguments.
Returns
Return type A list of edge keys assigned to the edges in ebunch.
See also:
Notes
Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments.
Default keys are generated using the method new_edge_key(). This method can be overridden by subclass-
ing the base class and providing a custom new_edge_key() method.
Examples
[Link].add_weighted_edges_from
Notes
Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph,
duplicate edges are stored.
Examples
[Link].new_edge_key
MultiGraph.new_edge_key(u, v)
Returns an unused key for edges between nodes u and v.
The nodes u and v do not need to be already in the graph.
Notes
In the standard MultiGraph class the new key is the number of existing edges between u and v (increased
if necessary to ensure unused). The first edge will have key 0, then 1, etc. If an edge is removed further
new_edge_keys may not be in this order.
Parameters u, v (nodes)
Returns key
Return type int
[Link].remove_edge
MultiGraph.remove_edge(u, v, key=None)
Remove an edge between u and v.
Parameters
• u, v (nodes) – Remove an edge between nodes u and v.
• key (hashable identifier, optional (default=None)) – Used to distinguish multiple edges be-
tween a pair of nodes. If None remove a single (arbitrary) edge between u and v.
Raises NetworkXError – If there is not an edge between u and v, or if there is no edge with the
specified key.
See also:
Examples
>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.remove_edge(0, 1)
>>> e = (1, 2)
>>> G.remove_edge(*e) # unpacks e from an edge tuple
[Link].remove_edges_from
MultiGraph.remove_edges_from(ebunch)
Remove all edges specified in ebunch.
Parameters ebunch (list or container of edge tuples) – Each edge given in the list or container will
be removed from the graph. The edges can be:
• 2-tuples (u, v) All edges between u and v are removed.
• 3-tuples (u, v, key) The edge identified by key is removed.
• 4-tuples (u, v, key, data) where data is ignored.
See also:
Notes
Examples
>>> G = [Link]()
>>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)])
>>> G.remove_edges_from([(1, 2), (1, 2)])
>>> list([Link]())
[(1, 2)]
>>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy
>>> list([Link]) # now empty graph
[]
[Link]
[Link](edges=None, nodes=None)
Update the graph using nodes/edges/graphs as input.
Like [Link], this method takes a graph as input, adding the graph’s nodes and edges to this graph. It can
also take two inputs: edges and nodes. Finally it can take either edges or nodes. To specify only nodes the
keyword nodes must be used.
The collections of edges and nodes are treated similarly to the add_edges_from/add_nodes_from methods.
When iterated, they should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
Parameters
• edges (Graph object, collection of edges, or None) – The first parameter can be a graph or
some edges. If it has attributes nodes and edges, then it is taken to be a Graph-like object
and those attributes are used as collections of nodes and edges to be added to the graph. If
the first parameter does not have those attributes, it is treated as a collection of edges and
added to the graph. If the first argument is None, no edges are added.
• nodes (collection of nodes, or None) – The second parameter is treated as a collection of
nodes to be added to the graph unless it is None. If edges is None and nodes is
None an exception is raised. If the first parameter is a Graph, then nodes is ignored.
Examples
>>> G = nx.path_graph(5)
>>> [Link](nx.complete_graph(range(4, 10)))
>>> from itertools import combinations
>>> edges = (
... (u, v, {"power": u * v})
... for u, v in combinations(range(10, 20), 2)
... if u * v < 225
... )
>>> nodes = [1000] # for singleton, use a container
>>> [Link](edges, nodes)
Notes
It you want to update the graph using an adjacency structure it is straightforward to obtain the edges/nodes from
adjacency. The following examples provide common cases, your adjacency may be slightly different and require
tweaks of these examples.
>>> # dict-of-set/list/tuple
>>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
>>> e = [(u, v) for u, nbrs in [Link]() for v in nbrs]
>>> [Link](edges=e, nodes=adj)
>>> DG = [Link]()
>>> # dict-of-dict-of-attribute
>>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
>>> e = [
... (u, v, {"weight": d})
... for u, nbrs in [Link]()
... for v, d in [Link]()
... ]
>>> [Link](edges=e, nodes=adj)
>>> # dict-of-dict-of-dict
>>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
>>> e = [
... (u, v, {"weight": d})
... for u, nbrs in [Link]()
... for v, d in [Link]()
... ]
>>> [Link](edges=e, nodes=adj)
See also:
[Link]
[Link]()
Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
Examples
[Link].clear_edges
MultiGraph.clear_edges()
Remove all edges from the graph without altering nodes.
Examples
[Link]
property [Link]
A NodeView of the Graph as [Link] or [Link]().
Can be used as [Link] for data lookup and for set-like operations. Can also be used as G.
nodes(data='color', default=None) to return a NodeDataView which reports specific node data
but no set operations. It presents a dict-like interface as well with [Link]() iterating over (node,
nodedata) 2-tuples and [Link][3]['foo'] providing the value of the foo attribute for node 3. In
addition, a view [Link]('foo') provides a dict-like interface to the foo attribute of each node.
[Link]('foo', default=1) provides a default for nodes that do not have attribute foo.
Parameters
• data (string or bool, optional (default=False)) – The node attribute returned in 2-tuple (n,
ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the
nodes n.
• default (value, optional (default=None)) – Value used for nodes that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns
Allows set-like operations over the nodes as well as node attribute dict lookup and calling to
get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A
NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node,
attribute value) where the attribute is specified in data. If data is True then the attribute becomes
the entire data dictionary.
Return type NodeView
Notes
If your node data is not needed, it is simpler and equivalent to use the expression for n in G, or list(G).
Examples
There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3)
>>> list([Link])
[0, 1, 2]
>>> list(G)
[0, 1, 2]
>>> list([Link](data="foo"))
[(0, 'bar'), (1, None), (2, None)]
>>> list([Link]("foo"))
[(0, 'bar'), (1, None), (2, None)]
>>> list([Link](data="time"))
[(0, None), (1, '5pm'), (2, None)]
>>> list([Link]("time"))
[(0, None), (1, '5pm'), (2, None)]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create
a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never
None:
>>> G = [Link]()
>>> G.add_node(0)
>>> G.add_node(1, weight=2)
>>> G.add_node(2, weight=3)
>>> dict([Link](data="weight", default=1))
{0: 1, 1: 2, 2: 3}
[Link].__iter__
MultiGraph.__iter__()
Iterate over the nodes. Use: ‘for n in G’.
Returns niter – An iterator over all nodes in the graph.
Return type iterator
Examples
[Link].has_node
MultiGraph.has_node(n)
Returns True if the graph contains the node n.
Identical to n in G
Parameters n (node)
Examples
[Link].__contains__
MultiGraph.__contains__(n)
Returns True if n is a node, False otherwise. Use: ‘n in G’.
Examples
[Link]
property [Link]
Returns an iterator over the edges.
edges(self, nbunch=None, data=False, keys=False, default=None)
The EdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called,
it also provides an EdgeDataView object which allows control of access to edge attributes (but does not pro-
vide set-like operations). Hence, [Link][u, v]['color'] provides the value of the color attribute for
edge (u, v) while for (u, v, c) in [Link](data='color', default='red'): iterates
through all the edges yielding the color attribute.
Edges are returned as tuples with optional data and keys in the order (node, neighbor, key, data).
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• keys (bool, optional (default=False)) – If True, return edge keys with each edge.
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) (u, v, k) or (u, v, k, d) tuples
of edges, but can also be used for attribute lookup as edges[u, v, k]['foo'].
Return type MultiEdgeView
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
[Link].has_edge
MultiGraph.has_edge(u, v, key=None)
Returns True if the graph has an edge between nodes u and v.
This is the same as v in G[u] or key in G[u][v] without KeyError exceptions.
Parameters
• u, v (nodes) – Nodes can be, for example, strings or numbers.
• key (hashable identifier, optional (default=None)) – If specified return True only if the edge
with key is found.
Returns edge_ind – True if edge is in the graph, False otherwise.
Return type bool
Examples
Can be called either using two nodes u, v, an edge tuple (u, v), or an edge tuple (u, v, key).
>>> G.has_edge(0, 1)
True
>>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G
True
[Link].get_edge_data
Examples
Warning: we protect the graph data structure by making [Link] and G[1][2] read-only dict-like structures.
However, you can assign values to attributes in e.g. [Link][1, 2, 'a'] or G[1][2]['a'] using an
additional bracket as shown next. You need to specify all edge info to assign to the edge data associated with an
edge.
>>> G[0][1]["a"]["weight"] = 10
>>> [Link][0, 1, "a"]["weight"] = 10
>>> G[0][1]["a"]["weight"]
10
>>> [Link][1, 0, "a"]["weight"]
10
[Link]
[Link](n)
Returns an iterator over all neighbors of node n.
This is identical to iter(G[n])
Parameters n (node) – A node in the graph
Returns neighbors – An iterator over all neighbors of node n
Return type iterator
Raises NetworkXError – If the node n is not in the graph.
Examples
Notes
[Link]
property [Link]
Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed
by neighbor to the edgekey-data-dict. So [Link][3][2][0]['color'] = 'blue' sets the color of the
edge (3, 2, 0) to "blue".
Iterating over [Link] behaves like a dict. Useful idioms include for nbr, nbrdict in [Link][n].
items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, [Link] holds outgoing (successor) info.
[Link].__getitem__
MultiGraph.__getitem__(n)
Returns a dict of neighbors of node n. Use: ‘G[n]’.
Parameters n (node) – A node in the graph.
Returns adj_dict – The adjacency dictionary for nodes connected to n.
Return type dictionary
Notes
G[n] is the same as [Link][n] and similar to [Link](n) (which is an iterator over [Link][n])
Examples
[Link]
[Link]()
Returns an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
Returns adj_iter – An iterator over (node, adjacency dictionary) for all nodes in the graph.
Return type iterator
Examples
[Link].nbunch_iter
MultiGraph.nbunch_iter(nbunch=None)
Returns an iterator over nodes contained in nbunch that are also in the graph.
The nodes in nbunch are checked for membership in the graph and if not are silently ignored.
Parameters nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
Returns niter – An iterator over nodes in nbunch that are also in the graph. If nbunch is None,
iterate over all nodes in the graph.
Return type iterator
Raises NetworkXError – If nbunch is not a node or or sequence of nodes. If a node in nbunch is
not hashable.
See also:
Graph.__iter__()
Notes
When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when
nbunch is exhausted.
To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a NetworkXError is raised. Also, if
any object in nbunch is not hashable, a NetworkXError is raised.
[Link]
[Link]()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), __len__()
Examples
[Link].number_of_nodes
MultiGraph.number_of_nodes()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
order(), __len__()
Examples
[Link].__len__
MultiGraph.__len__()
Returns the number of nodes in the graph. Use: ‘len(G)’.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), order()
Examples
[Link]
property [Link]
A DegreeView for the Graph as [Link] or [Link]().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge
weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an edge attribute that holds
the numerical value used as a weight. If None, then each edge has weight 1. The degree is
the sum of the edge weights adjacent to the node.
Returns
• If a single node is requested
• deg (int) – Degree of the node, if a single node is passed as argument.
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, degree).
Examples
[Link]
[Link](weight=None)
Returns the number of edges or total of all edge weights.
Parameters weight (string or None, optional (default=None)) – The edge attribute that holds the
numerical value used as a weight. If None, then each edge has weight 1.
Returns
size – The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are
more general).
Examples
[Link].number_of_edges
MultiGraph.number_of_edges(u=None, v=None)
Returns the number of edges between two nodes.
Parameters u, v (nodes, optional (Gefault=all edges)) – If u and v are specified, return the number
of edges between u and v. Otherwise return the total number of all edges.
Returns nedges – The number of edges in the graph. If nodes u and v are specified return the
number of edges between those nodes. If the graph is directed, this only returns the number of
edges from u to v.
Return type int
See also:
size()
Examples
For undirected multigraphs, this method counts the total number of edges in the graph:
>>> G = [Link]()
>>> G.add_edges_from([(0, 1), (0, 1), (1, 2)])
[0, 1, 0]
>>> G.number_of_edges()
3
If you specify two nodes, this counts the total number of edges joining the two nodes:
>>> G.number_of_edges(0, 1)
2
For directed multigraphs, this method can count the total number of directed edges from u to v:
>>> G = [Link]()
>>> G.add_edges_from([(0, 1), (0, 1), (1, 0)])
[0, 1, 0]
>>> G.number_of_edges(0, 1)
2
>>> G.number_of_edges(1, 0)
1
[Link]
[Link](as_view=False)
Returns a copy of the graph.
The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an
attribute is a container, that container is shared by the original an the copy. Use Python’s [Link] for
new containers.
If as_view is True then a view is returned instead of a copy.
Notes
All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four
types of copies of a graph that people might want.
Deepcopy – A “deepcopy” copies the graph structure as well as all data attributes and any objects they might
contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s
[Link])
Data Reference (Shallow) – For a shallow copy the graph structure is copied but the edge, node and graph at-
tribute dicts are references to those in the original graph. This saves time and memory but could cause confusion
if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this
level of shallow copy.
Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the
attributes. That is, any attributes that are containers are shared between the new graph and the original. This is
exactly what [Link]() provides. You can obtain this style copy using:
>>> G = nx.path_graph(5)
>>> H = [Link]()
>>> H = [Link](as_view=False)
>>> H = [Link](G)
>>> H = G.__class__(G)
Fresh Data – For fresh data, the graph structure is copied while new empty data attribute dicts are created. The
resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not
enabled. Instead use:
>>> H = G.__class__()
>>> H.add_nodes_from(G)
>>> H.add_edges_from([Link])
View – Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy
of the original structure without requiring any memory for copying the information.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Parameters as_view (bool, optional (default=False)) – If True, the returned graph-view provides a
read-only view of the original graph without actually copying any data.
Returns G – A copy of the graph.
Return type Graph
See also:
Examples
[Link].to_undirected
MultiGraph.to_undirected(as_view=False)
Returns an undirected copy of the graph.
Returns G – A deepcopy of the graph.
Return type Graph/MultiGraph
See also:
copy(), add_edge(), add_edges_from()
Notes
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar G = [Link](D) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Warning: If you have subclassed MultiiGraph to use dict-like objects in the data structure, those changes do not
transfer to the MultiGraph created by this method.
Examples
[Link].to_directed
MultiGraph.to_directed(as_view=False)
Returns a directed representation of the graph.
Returns G – A directed graph with the same name, same nodes, and with each edge (u, v, data)
replaced by two directed edges (u, v, data) and (v, u, data).
Return type MultiDiGraph
Notes
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Warning: If you have subclassed MultiGraph to use dict-like objects in the data structure, those changes do not
transfer to the MultiDiGraph created by this method.
Examples
[Link]
[Link](nodes)
Returns a SubGraph view of the subgraph induced on nodes.
The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.
Parameters nodes (list, iterable) – A container of nodes which will be iterated through once.
Returns G – A subgraph view of the graph. The graph structure cannot be changed but node/edge
attributes can and are shared with the original graph.
Return type SubGraph View
Notes
The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled
out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: [Link](nodes).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([n for n in G
if n not in set(nodes)])
Subgraph views are sometimes NOT what you want. In most cases where you want to do more than simply look
at the induced edges, it makes more sense to just create the subgraph as its own graph with code like:
Examples
[Link].edge_subgraph
MultiGraph.edge_subgraph(edges)
Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any one of those edges.
Parameters edges (iterable) – An iterable of edges in this graph.
Returns G – An edge-induced subgraph of this graph with the same edge attributes.
Return type Graph
Notes
The graph, edge, and node attributes in the returned subgraph view are references to the corresponding attributes
in the original graph. The view is read-only.
To create a full graph version of the subgraph with its own copy of the edge or node attributes, use:
>>> G.edge_subgraph(edges).copy()
Examples
>>> G = nx.path_graph(5)
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
>>> list([Link])
[0, 1, 3, 4]
>>> list([Link])
[(0, 1), (3, 4)]
Overview
See also:
Graph, DiGraph, MultiGraph, OrderedMultiDiGraph
Examples
Create an empty graph structure (a “null graph”) with no nodes and no edges.
>>> G = [Link]()
>>> G.add_node(1)
Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).
In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a
customized node object, or even another Graph.
>>> G.add_node(H)
Edges:
G can also be grown by adding edges.
Add one edge,
a list of edges,
or a collection of edges,
If some edges connect nodes not yet in the graph, the nodes are added automatically. If an edge already exists,
an additional edge is created and stored using a key to identify the edge. By default the key is the lowest unused
integer.
Attributes:
Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys
must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct
manipulation of the attribute dictionaries named graph, node and edge respectively.
>>> G = [Link](day="Friday")
>>> [Link]
{'day': 'Friday'}
Warning: we protect the graph data structure by making [Link][1, 2] a read-only dict-like structure.
However, you can assign to attributes in e.g. [Link][1, 2]. Thus, use 2 sets of brackets to add/change data
attributes: [Link][1, 2]['weight'] = 4 (For multigraphs: [Link][u, v, key][name] =
value).
Shortcuts:
Many common graph features allow python syntax to speed reporting.
Often the best way to traverse all edges of a graph is via the neighbors. The neighbors are available as an
adjacency-view [Link] object or via the method [Link]().
Reporting:
Simple graph information is obtained using methods and object-attributes. Reporting usually provides
views instead of containers to reduce memory usage. The views update as the graph is updated simi-
larly to dict-views. The objects nodes, `edges and adj provide access to data attributes via lookup
(e.g. nodes[n], `edges[u, v], adj[u][v]) and iteration (e.g. [Link](), nodes.
data('color'), [Link]('color', default='blue') and similarly for edges) Views exist
for nodes, edges, neighbors()/adj and degree.
For details on these and other miscellaneous methods, see below.
Subclasses (Advanced):
The MultiDiGraph class uses a dict-of-dict-of-dict-of-dict structure. The outer dict (node_dict) holds adjacency
information keyed by node. The next dict (adjlist_dict) represents the adjacency information and holds edge_key
dicts keyed by neighbor. The edge_key dict holds each edge_attr dict keyed by edge key. The inner dict
(edge_attr_dict) represents the edge data and holds edge attribute values keyed by attribute names.
Each of these four dicts in the dict-of-dict-of-dict-of-dict structure can be replaced by a user defined dict-like
object. In general, the dict-like features should be maintained but extra features can be added. To replace
one of the dicts create a new graph class by changing the class(!) variable holding the factory for that dict-
like structure. The variable names are node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory and graph_attr_dict_factory.
node_dict_factory [function, (default: dict)] Factory function to be used to create the dict containing node
attributes, keyed by node id. It should require no arguments and return a dict-like object
node_attr_dict_factory: function, (default: dict) Factory function to be used to create the node attribute dict
which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like
object
adjlist_outer_dict_factory [function, (default: dict)] Factory function to be used to create the outer-most dict
in the data structure that holds adjacency info keyed by node. It should require no arguments and return a
dict-like object.
adjlist_inner_dict_factory [function, (default: dict)] Factory function to be used to create the adjacency list
dict which holds multiedge key dicts keyed by neighbor. It should require no arguments and return a
dict-like object.
edge_key_dict_factory [function, (default: dict)] Factory function to be used to create the edge key dict which
holds edge data keyed by edge key. It should require no arguments and return a dict-like object.
edge_attr_dict_factory [function, (default: dict)] Factory function to be used to create the edge attribute dict
which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like
object.
graph_attr_dict_factory [function, (default: dict)] Factory function to be used to create the graph attribute
dict which holds attribute values keyed by attribute name. It should require no arguments and return a
dict-like object.
Typically, if your extension doesn’t impact the data structure all methods will inherited without issue except:
to_directed/to_undirected. By default these methods create a DiGraph/Graph class and you probably
want them to create your extension of a DiGraph/Graph. To facilitate this we define two class variables that you
can set in your subclass.
to_directed_class [callable, (default: DiGraph or MultiDiGraph)] Class to create a new graph structure in the
to_directed method. If None, a NetworkX class (DiGraph or MultiDiGraph) is used.
to_undirected_class [callable, (default: Graph or MultiGraph)] Class to create a new graph structure in the
to_undirected method. If None, a NetworkX class (Graph or MultiGraph) is used.
Examples
Please see ordered for examples of creating graph subclasses by overwriting the base class dict with a
dictionary-like object.
Methods
[Link].__init__
MultiDiGraph.__init__(incoming_graph_data=None, **attr)
Initialize a graph with edges, name, or graph attributes.
Parameters
• incoming_graph_data (input graph) – Data to initialize graph. If incom-
ing_graph_data=None (default) an empty graph is created. The data can be an edge list,
or any NetworkX graph object. If the corresponding optional Python packages are installed
the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz
graph.
• attr (keyword arguments, optional (default= no attributes)) – Attributes to add to graph as
key=value pairs.
See also:
convert()
Examples
[Link].add_node
MultiDiGraph.add_node(node_for_adding, **attr)
Add a single node node_for_adding and update node attributes.
Parameters
• node_for_adding (node) – A node can be any hashable Python object except None.
• attr (keyword arguments, optional) – Set or change node attributes using key=value.
See also:
add_nodes_from()
Examples
Notes
A hashable object is one that can be used as a key in a Python dictionary. This includes strings, numbers, tuples
of strings and numbers, etc.
On many platforms hashable items also include mutables such as NetworkX Graphs, though one should be
careful that the hash doesn’t change on mutables.
[Link].add_nodes_from
MultiDiGraph.add_nodes_from(nodes_for_adding, **attr)
Add multiple nodes.
Parameters
• nodes_for_adding (iterable container) – A container of nodes (list, dict, set, etc.). OR A
container of (node, attribute dict) tuples. Node attributes are updated using the attribute dict.
• attr (keyword arguments, optional (default= no attributes)) – Update attributes for all nodes
in nodes. Node attributes specified in nodes as a tuple take precedence over attributes spec-
ified via keyword arguments.
See also:
add_node()
Examples
[Link].remove_node
MultiDiGraph.remove_node(n)
Remove node n.
Removes the node n and all adjacent edges. Attempting to remove a non-existent node will raise an exception.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
remove_nodes_from()
Examples
[Link].remove_nodes_from
MultiDiGraph.remove_nodes_from(nodes)
Remove multiple nodes.
Parameters nodes (iterable container) – A container of nodes (list, dict, set, etc.). If a node in the
container is not in the graph it is silently ignored.
See also:
remove_node()
Examples
[Link].add_edge
Notes
To replace/update edge data, use the optional key argument to identify a unique edge. Otherwise a new edge
will be created.
NetworkX algorithms designed for weighted graphs cannot use multigraphs directly because it is not clear
how to handle multiedge weights. Convert to Graph using edge attribute ‘weight’ to enable weighted graph
algorithms.
Default keys are generated using the method new_edge_key(). This method can be overridden by subclass-
ing the base class and providing a custom new_edge_key() method.
Examples
>>> G = [Link]()
>>> e = (1, 2)
>>> key = G.add_edge(1, 2) # explicit two-node form
>>> G.add_edge(*e) # single edge as tuple of two nodes
1
>>> G.add_edges_from([(1, 2)]) # add edges from iterable container
[2]
[Link].add_edges_from
MultiDiGraph.add_edges_from(ebunch_to_add, **attr)
Add all the edges in ebunch_to_add.
Parameters
• ebunch_to_add (container of edges) – Each edge given in the container will be added to
the graph. The edges can be:
– 2-tuples (u, v) or
– 3-tuples (u, v, d) for an edge data dict d, or
– 3-tuples (u, v, k) for not iterable key k, or
Notes
Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments.
Default keys are generated using the method new_edge_key(). This method can be overridden by subclass-
ing the base class and providing a custom new_edge_key() method.
Examples
[Link].add_weighted_edges_from
Notes
Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph,
duplicate edges are stored.
Examples
[Link].new_edge_key
MultiDiGraph.new_edge_key(u, v)
Returns an unused key for edges between nodes u and v.
The nodes u and v do not need to be already in the graph.
Notes
In the standard MultiGraph class the new key is the number of existing edges between u and v (increased
if necessary to ensure unused). The first edge will have key 0, then 1, etc. If an edge is removed further
new_edge_keys may not be in this order.
Parameters u, v (nodes)
Returns key
Return type int
[Link].remove_edge
MultiDiGraph.remove_edge(u, v, key=None)
Remove an edge between u and v.
Parameters
• u, v (nodes) – Remove an edge between nodes u and v.
• key (hashable identifier, optional (default=None)) – Used to distinguish multiple edges be-
tween a pair of nodes. If None remove a single (arbitrary) edge between u and v.
Raises NetworkXError – If there is not an edge between u and v, or if there is no edge with the
specified key.
See also:
Examples
>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.remove_edge(0, 1)
>>> e = (1, 2)
>>> G.remove_edge(*e) # unpacks e from an edge tuple
>>> G = [Link]()
>>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
[0, 1, 2]
>>> G.remove_edge(1, 2) # remove a single (arbitrary) edge
>>> G = [Link]()
>>> G.add_edge(1, 2, key="first")
'first'
>>> G.add_edge(1, 2, key="second")
'second'
>>> G.remove_edge(1, 2, key="second")
[Link].remove_edges_from
MultiDiGraph.remove_edges_from(ebunch)
Remove all edges specified in ebunch.
Parameters ebunch (list or container of edge tuples) – Each edge given in the list or container will
be removed from the graph. The edges can be:
• 2-tuples (u, v) All edges between u and v are removed.
• 3-tuples (u, v, key) The edge identified by key is removed.
• 4-tuples (u, v, key, data) where data is ignored.
See also:
Notes
Examples
>>> G = [Link]()
>>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)])
>>> G.remove_edges_from([(1, 2), (1, 2)])
>>> list([Link]())
[(1, 2)]
>>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy
>>> list([Link]) # now empty graph
[]
[Link]
[Link](edges=None, nodes=None)
Update the graph using nodes/edges/graphs as input.
Like [Link], this method takes a graph as input, adding the graph’s nodes and edges to this graph. It can
also take two inputs: edges and nodes. Finally it can take either edges or nodes. To specify only nodes the
keyword nodes must be used.
The collections of edges and nodes are treated similarly to the add_edges_from/add_nodes_from methods.
When iterated, they should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
Parameters
• edges (Graph object, collection of edges, or None) – The first parameter can be a graph or
some edges. If it has attributes nodes and edges, then it is taken to be a Graph-like object
and those attributes are used as collections of nodes and edges to be added to the graph. If
the first parameter does not have those attributes, it is treated as a collection of edges and
added to the graph. If the first argument is None, no edges are added.
• nodes (collection of nodes, or None) – The second parameter is treated as a collection of
nodes to be added to the graph unless it is None. If edges is None and nodes is
None an exception is raised. If the first parameter is a Graph, then nodes is ignored.
Examples
>>> G = nx.path_graph(5)
>>> [Link](nx.complete_graph(range(4, 10)))
>>> from itertools import combinations
>>> edges = (
... (u, v, {"power": u * v})
... for u, v in combinations(range(10, 20), 2)
... if u * v < 225
... )
>>> nodes = [1000] # for singleton, use a container
>>> [Link](edges, nodes)
Notes
It you want to update the graph using an adjacency structure it is straightforward to obtain the edges/nodes from
adjacency. The following examples provide common cases, your adjacency may be slightly different and require
tweaks of these examples.
>>> # dict-of-set/list/tuple
>>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
>>> e = [(u, v) for u, nbrs in [Link]() for v in nbrs]
>>> [Link](edges=e, nodes=adj)
>>> DG = [Link]()
>>> # dict-of-dict-of-attribute
>>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
>>> e = [
... (u, v, {"weight": d})
... for u, nbrs in [Link]()
... for v, d in [Link]()
... ]
>>> [Link](edges=e, nodes=adj)
>>> # dict-of-dict-of-dict
>>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
>>> e = [
... (u, v, {"weight": d})
... for u, nbrs in [Link]()
... for v, d in [Link]()
... ]
>>> [Link](edges=e, nodes=adj)
See also:
[Link]
[Link]()
Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
Examples
[Link].clear_edges
MultiDiGraph.clear_edges()
Remove all edges from the graph without altering nodes.
Examples
[Link]
property [Link]
A NodeView of the Graph as [Link] or [Link]().
Can be used as [Link] for data lookup and for set-like operations. Can also be used as G.
nodes(data='color', default=None) to return a NodeDataView which reports specific node data
but no set operations. It presents a dict-like interface as well with [Link]() iterating over (node,
nodedata) 2-tuples and [Link][3]['foo'] providing the value of the foo attribute for node 3. In
addition, a view [Link]('foo') provides a dict-like interface to the foo attribute of each node.
[Link]('foo', default=1) provides a default for nodes that do not have attribute foo.
Parameters
• data (string or bool, optional (default=False)) – The node attribute returned in 2-tuple (n,
ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the
nodes n.
• default (value, optional (default=None)) – Value used for nodes that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns
Allows set-like operations over the nodes as well as node attribute dict lookup and calling to
get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A
NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node,
attribute value) where the attribute is specified in data. If data is True then the attribute becomes
the entire data dictionary.
Return type NodeView
Notes
If your node data is not needed, it is simpler and equivalent to use the expression for n in G, or list(G).
Examples
There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3)
>>> list([Link])
[0, 1, 2]
>>> list(G)
[0, 1, 2]
>>> list([Link](data="foo"))
[(0, 'bar'), (1, None), (2, None)]
>>> list([Link]("foo"))
[(0, 'bar'), (1, None), (2, None)]
>>> list([Link](data="time"))
[(0, None), (1, '5pm'), (2, None)]
>>> list([Link]("time"))
[(0, None), (1, '5pm'), (2, None)]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create
a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never
None:
>>> G = [Link]()
>>> G.add_node(0)
>>> G.add_node(1, weight=2)
>>> G.add_node(2, weight=3)
>>> dict([Link](data="weight", default=1))
{0: 1, 1: 2, 2: 3}
[Link].__iter__
MultiDiGraph.__iter__()
Iterate over the nodes. Use: ‘for n in G’.
Returns niter – An iterator over all nodes in the graph.
Return type iterator
Examples
[Link].has_node
MultiDiGraph.has_node(n)
Returns True if the graph contains the node n.
Identical to n in G
Parameters n (node)
Examples
>>> 0 in G
True
[Link].__contains__
MultiDiGraph.__contains__(n)
Returns True if n is a node, False otherwise. Use: ‘n in G’.
Examples
[Link]
property [Link]
An OutMultiEdgeView of the Graph as [Link] or [Link]().
edges(self, nbunch=None, data=False, keys=False, default=None)
The OutMultiEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When
called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not
provide set-like operations). Hence, [Link][u, v]['color'] provides the value of the color attribute
for edge (u, v) while for (u, v, c) in [Link](data='color', default='red'): iter-
ates through all the edges yielding the color attribute with default 'red' if no color attribute exists.
Edges are returned as tuples with optional data and keys in the order (node, neighbor, key, data).
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• keys (bool, optional (default=False)) – If True, return edge keys with each edge.
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) (u, v, k) or (u, v, k, d) tuples
of edges, but can also be used for attribute lookup as edges[u, v, k]['foo'].
Return type EdgeView
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2])
>>> key = G.add_edge(2, 3, weight=5)
>>> [e for e in [Link]()]
[(0, 1), (1, 2), (2, 3)]
>>> list([Link](data=True)) # default data is {} (empty dict)
[(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})]
>>> list([Link](data="weight", default=1))
[(0, 1, 1), (1, 2, 1), (2, 3, 5)]
>>> list([Link](keys=True)) # default keys are integers
(continues on next page)
See also:
in_edges, out_edges
[Link].out_edges
property MultiDiGraph.out_edges
An OutMultiEdgeView of the Graph as [Link] or [Link]().
edges(self, nbunch=None, data=False, keys=False, default=None)
The OutMultiEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When
called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not
provide set-like operations). Hence, [Link][u, v]['color'] provides the value of the color attribute
for edge (u, v) while for (u, v, c) in [Link](data='color', default='red'): iter-
ates through all the edges yielding the color attribute with default 'red' if no color attribute exists.
Edges are returned as tuples with optional data and keys in the order (node, neighbor, key, data).
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• keys (bool, optional (default=False)) – If True, return edge keys with each edge.
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) (u, v, k) or (u, v, k, d) tuples
of edges, but can also be used for attribute lookup as edges[u, v, k]['foo'].
Return type EdgeView
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2])
>>> key = G.add_edge(2, 3, weight=5)
>>> [e for e in [Link]()]
[(0, 1), (1, 2), (2, 3)]
>>> list([Link](data=True)) # default data is {} (empty dict)
[(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})]
>>> list([Link](data="weight", default=1))
[(0, 1, 1), (1, 2, 1), (2, 3, 5)]
>>> list([Link](keys=True)) # default keys are integers
[(0, 1, 0), (1, 2, 0), (2, 3, 0)]
>>> list([Link](data=True, keys=True))
[(0, 1, 0, {}), (1, 2, 0, {}), (2, 3, 0, {'weight': 5})]
>>> list([Link](data="weight", default=1, keys=True))
[(0, 1, 0, 1), (1, 2, 0, 1), (2, 3, 0, 5)]
>>> list([Link]([0, 2]))
[(0, 1), (2, 3)]
>>> list([Link](0))
[(0, 1)]
See also:
in_edges, out_edges
[Link].in_edges
property MultiDiGraph.in_edges
An InMultiEdgeView of the Graph as G.in_edges or G.in_edges().
in_edges(self, nbunch=None, data=False, keys=False, default=None)
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• keys (bool, optional (default=False)) – If True, return edge keys with each edge.
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns in_edges – A view of edge attributes, usually it iterates over (u, v) or (u, v, k) or (u, v, k, d)
tuples of edges, but can also be used for attribute lookup as edges[u, v, k]['foo'].
Return type InMultiEdgeView
See also:
edges
[Link].has_edge
MultiDiGraph.has_edge(u, v, key=None)
Returns True if the graph has an edge between nodes u and v.
This is the same as v in G[u] or key in G[u][v] without KeyError exceptions.
Parameters
• u, v (nodes) – Nodes can be, for example, strings or numbers.
• key (hashable identifier, optional (default=None)) – If specified return True only if the edge
with key is found.
Returns edge_ind – True if edge is in the graph, False otherwise.
Return type bool
Examples
Can be called either using two nodes u, v, an edge tuple (u, v), or an edge tuple (u, v, key).
>>> G.has_edge(0, 1)
True
>>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G
True
[Link].get_edge_data
• key (hashable identifier, optional (default=None)) – Return data only for the edge with
specified key.
Returns edge_dict – The edge attribute dictionary.
Return type dictionary
Examples
Warning: we protect the graph data structure by making [Link] and G[1][2] read-only dict-like structures.
However, you can assign values to attributes in e.g. [Link][1, 2, 'a'] or G[1][2]['a'] using an
additional bracket as shown next. You need to specify all edge info to assign to the edge data associated with an
edge.
>>> G[0][1]["a"]["weight"] = 10
>>> [Link][0, 1, "a"]["weight"] = 10
>>> G[0][1]["a"]["weight"]
10
>>> [Link][1, 0, "a"]["weight"]
10
[Link]
[Link](n)
Returns an iterator over successor nodes of n.
A successor of n is a node m such that there exists a directed edge from n to m.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
predecessors()
Notes
[Link]
property [Link]
Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed
by neighbor to the edgekey-dict. So [Link][3][2][0]['color'] = 'blue' sets the color of the edge
(3, 2, 0) to "blue".
Iterating over [Link] behaves like a dict. Useful idioms include for nbr, datadict in [Link][n].
items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, [Link] holds outgoing (successor) info.
[Link].__getitem__
MultiDiGraph.__getitem__(n)
Returns a dict of neighbors of node n. Use: ‘G[n]’.
Parameters n (node) – A node in the graph.
Returns adj_dict – The adjacency dictionary for nodes connected to n.
Return type dictionary
Notes
G[n] is the same as [Link][n] and similar to [Link](n) (which is an iterator over [Link][n])
Examples
[Link]
[Link](n)
Returns an iterator over successor nodes of n.
A successor of n is a node m such that there exists a directed edge from n to m.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
predecessors()
Notes
[Link]
property [Link]
Graph adjacency object holding the successors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed
by neighbor to the edgekey-dict. So [Link][3][2][0]['color'] = 'blue' sets the color of the edge
(3, 2, 0) to "blue".
Iterating over [Link] behaves like a dict. Useful idioms include for nbr, datadict in [Link][n].
items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, [Link] is identical to [Link].
[Link]
[Link](n)
Returns an iterator over predecessor nodes of n.
A predecessor of n is a node m such that there exists a directed edge from m to n.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
successors()
[Link]
[Link]()
Returns an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
Returns adj_iter – An iterator over (node, adjacency dictionary) for all nodes in the graph.
Return type iterator
Examples
[Link].nbunch_iter
MultiDiGraph.nbunch_iter(nbunch=None)
Returns an iterator over nodes contained in nbunch that are also in the graph.
The nodes in nbunch are checked for membership in the graph and if not are silently ignored.
Parameters nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
Returns niter – An iterator over nodes in nbunch that are also in the graph. If nbunch is None,
iterate over all nodes in the graph.
Return type iterator
Raises NetworkXError – If nbunch is not a node or or sequence of nodes. If a node in nbunch is
not hashable.
See also:
Graph.__iter__()
Notes
When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when
nbunch is exhausted.
To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a NetworkXError is raised. Also, if
any object in nbunch is not hashable, a NetworkXError is raised.
[Link]
[Link]()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), __len__()
Examples
[Link].number_of_nodes
MultiDiGraph.number_of_nodes()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
order(), __len__()
Examples
[Link].__len__
MultiDiGraph.__len__()
Returns the number of nodes in the graph. Use: ‘len(G)’.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), order()
Examples
[Link]
property [Link]
A DegreeView for the Graph as [Link] or [Link]().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge
weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an edge attribute that holds
the numerical value used as a weight. If None, then each edge has weight 1. The degree is
the sum of the edge weights adjacent to the node.
Returns
• If a single nodes is requested
• deg (int) – Degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, degree).
See also:
out_degree, in_degree
Examples
>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> [Link](0) # node 0 with degree 1
1
>>> list([Link]([0, 1, 2]))
[(0, 1), (1, 2), (2, 2)]
[Link].in_degree
property MultiDiGraph.in_degree
A DegreeView for (node, in_degree) or in_degree for single node.
The node in-degree is the number of edges pointing in to the node. The weighted node degree is the sum of the
edge weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1. The degree is the sum of
the edge weights adjacent to the node.
Returns
• If a single node is requested
• deg (int) – Degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, in-degree).
See also:
degree, out_degree
Examples
>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.in_degree(0) # node 0 with degree 0
0
>>> list(G.in_degree([0, 1, 2]))
[(0, 0), (1, 1), (2, 1)]
[Link].out_degree
property MultiDiGraph.out_degree
Returns an iterator for (node, out-degree) or out-degree for single node.
out_degree(self, nbunch=None, weight=None)
The node out-degree is the number of edges pointing out of the node. This function returns the out-degree for a
single node or an iterator for a bunch of nodes or if nothing is passed as argument.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1. The degree is the sum of
the edge weights.
Returns
• If a single node is requested
• deg (int) – Degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, out-degree).
See also:
degree, in_degree
Examples
>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.out_degree(0) # node 0 with degree 1
1
>>> list(G.out_degree([0, 1, 2]))
[(0, 1), (1, 1), (2, 1)]
[Link]
[Link](weight=None)
Returns the number of edges or total of all edge weights.
Parameters weight (string or None, optional (default=None)) – The edge attribute that holds the
numerical value used as a weight. If None, then each edge has weight 1.
Returns
size – The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are
more general).
Return type numeric
See also:
number_of_edges()
Examples
[Link].number_of_edges
MultiDiGraph.number_of_edges(u=None, v=None)
Returns the number of edges between two nodes.
Parameters u, v (nodes, optional (Gefault=all edges)) – If u and v are specified, return the number
of edges between u and v. Otherwise return the total number of all edges.
Returns nedges – The number of edges in the graph. If nodes u and v are specified return the
number of edges between those nodes. If the graph is directed, this only returns the number of
edges from u to v.
Return type int
See also:
size()
Examples
For undirected multigraphs, this method counts the total number of edges in the graph:
>>> G = [Link]()
>>> G.add_edges_from([(0, 1), (0, 1), (1, 2)])
[0, 1, 0]
>>> G.number_of_edges()
3
If you specify two nodes, this counts the total number of edges joining the two nodes:
>>> G.number_of_edges(0, 1)
2
For directed multigraphs, this method can count the total number of directed edges from u to v:
>>> G = [Link]()
>>> G.add_edges_from([(0, 1), (0, 1), (1, 0)])
[0, 1, 0]
>>> G.number_of_edges(0, 1)
2
>>> G.number_of_edges(1, 0)
1
[Link]
[Link](as_view=False)
Returns a copy of the graph.
The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an
attribute is a container, that container is shared by the original an the copy. Use Python’s [Link] for
new containers.
If as_view is True then a view is returned instead of a copy.
Notes
All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four
types of copies of a graph that people might want.
Deepcopy – A “deepcopy” copies the graph structure as well as all data attributes and any objects they might
contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s
[Link])
Data Reference (Shallow) – For a shallow copy the graph structure is copied but the edge, node and graph at-
tribute dicts are references to those in the original graph. This saves time and memory but could cause confusion
if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this
level of shallow copy.
Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the
attributes. That is, any attributes that are containers are shared between the new graph and the original. This is
exactly what [Link]() provides. You can obtain this style copy using:
>>> G = nx.path_graph(5)
>>> H = [Link]()
>>> H = [Link](as_view=False)
>>> H = [Link](G)
>>> H = G.__class__(G)
Fresh Data – For fresh data, the graph structure is copied while new empty data attribute dicts are created. The
resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not
enabled. Instead use:
>>> H = G.__class__()
>>> H.add_nodes_from(G)
>>> H.add_edges_from([Link])
View – Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy
of the original structure without requiring any memory for copying the information.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Parameters as_view (bool, optional (default=False)) – If True, the returned graph-view provides a
read-only view of the original graph without actually copying any data.
Returns G – A copy of the graph.
Return type Graph
See also:
Examples
[Link].to_undirected
MultiDiGraph.to_undirected(reciprocal=False, as_view=False)
Returns an undirected representation of the digraph.
Parameters
• reciprocal (bool (optional)) – If True only keep edges that appear in both directions in the
original digraph.
• as_view (bool (optional, default=False)) – If True return an undirected view of the original
directed graph.
Returns G – An undirected graph with the same name and nodes and with edge (u, v, data) if either
(u, v, data) or (v, u, data) is in the digraph. If both edges exist in digraph and their edge data is
different, only one edge is created with an arbitrary choice of which edge data to use. You must
check and correct for this manually if desired.
Return type MultiGraph
See also:
MultiGraph(), copy(), add_edge(), add_edges_from()
Notes
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar D=MultiiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Warning: If you have subclassed MultiDiGraph to use dict-like objects in the data structure, those changes do
not transfer to the MultiGraph created by this method.
Examples
[Link].to_directed
MultiDiGraph.to_directed(as_view=False)
Returns a directed representation of the graph.
Returns G – A directed graph with the same name, same nodes, and with each edge (u, v, data)
replaced by two directed edges (u, v, data) and (v, u, data).
Return type MultiDiGraph
Notes
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, [Link]
[Link].
Warning: If you have subclassed MultiGraph to use dict-like objects in the data structure, those changes do not
transfer to the MultiDiGraph created by this method.
Examples
[Link]
[Link](nodes)
Returns a SubGraph view of the subgraph induced on nodes.
The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.
Parameters nodes (list, iterable) – A container of nodes which will be iterated through once.
Returns G – A subgraph view of the graph. The graph structure cannot be changed but node/edge
attributes can and are shared with the original graph.
Return type SubGraph View
Notes
The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled
out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: [Link](nodes).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([n for n in G
if n not in set(nodes)])
Subgraph views are sometimes NOT what you want. In most cases where you want to do more than simply look
at the induced edges, it makes more sense to just create the subgraph as its own graph with code like:
Examples
[Link].edge_subgraph
MultiDiGraph.edge_subgraph(edges)
Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any one of those edges.
Parameters edges (iterable) – An iterable of edges in this graph.
Returns G – An edge-induced subgraph of this graph with the same edge attributes.
Return type Graph
Notes
The graph, edge, and node attributes in the returned subgraph view are references to the corresponding attributes
in the original graph. The view is read-only.
To create a full graph version of the subgraph with its own copy of the edge or node attributes, use:
>>> G.edge_subgraph(edges).copy()
Examples
>>> G = nx.path_graph(5)
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
>>> list([Link])
[0, 1, 3, 4]
>>> list([Link])
[(0, 1), (3, 4)]
[Link]
[Link](copy=True)
Returns the reverse of the graph.
The reverse is a graph with the same nodes and edges but with the directions of the edges reversed.
Parameters copy (bool optional (default=True)) – If True, return a new DiGraph holding the re-
versed edges. If False, the reverse graph is created using a view of the original graph.
Consistently ordered variants of the default base classes. Note that if you are using Python 3.6+, you shouldn’t need
these classes because the dicts in Python 3.6+ are ordered. Note also that there are many differing expectations for the
word “ordered” and that these classes may not provide the order you expect. The intent here is to give a consistent
order not a particular order.
The Ordered (Di/Multi/MultiDi) Graphs give a consistent order for reporting of nodes and edges. The order of node
reporting agrees with node adding, but for edges, the order is not necessarily the order that the edges were added.
In general, you should use the default (i.e., unordered) graph classes. However, there are times (e.g., when testing)
when you may need the order preserved.
Special care is required when using subgraphs of the Ordered classes. The order of nodes in the subclass is not
necessarily the same order as the original class. In general it is probably better to avoid using subgraphs and replace
with code similar to:
# instead of SG = [Link](ordered_nodes)
SG = [Link]()
SG.add_nodes_from(ordered_nodes)
SG.add_edges_from((u, v) for (u, v) in [Link]() if u in SG if v in SG)
Note: NetworkX uses dicts to store the nodes and neighbors in a graph. So the reporting of nodes and edges for
the base graph classes will not necessarily be consistent across versions and platforms. If you need the order of nodes
and edges to be consistent (e.g., when writing automated tests), please see OrderedGraph, OrderedDiGraph,
OrderedMultiGraph, or OrderedMultiDiGraph, which behave like the base graph classes but give a consis-
tent order for reporting of nodes and edges.
generic_graph_view(G[, create_using])
subgraph_view(G[, filter_node, filter_edge]) View of G applying a filter on nodes and edges.
reverse_view(G) View of G with edge directions reversed
2.3.1 [Link].generic_graph_view
generic_graph_view(G, create_using=None)
2.3.2 [Link].subgraph_view
Both node and edge filter functions are called on graph elements as they are queried, meaning there is no up-front
cost to creating the view.
Parameters
• G ([Link]) – A directed/undirected graph/multigraph
• filter_node (callable, optional) – A function taking a node as input, which returns True if
the node should appear in the view.
• filter_edge (callable, optional) – A function taking as input the two nodes describing an
edge (plus the edge-key if G is a multi-graph), which returns True if the edge should appear
in the view.
Returns graph – A read-only graph view of the input graph.
Return type [Link]
Examples
>>> G = nx.path_graph(6)
Filter functions operate on the node, and return True if the node should appear in the view:
We can use a closure pattern to filter graph elements based on additional data — for example, filtering on edge
data attached to the graph:
2.3.3 [Link].reverse_view
reverse_view(G)
View of G with edge directions reversed
reverse_view returns a read-only view of the input graph where edge directions are reversed.
Identical to [Link](copy=False)
Parameters G ([Link])
Returns graph
Return type [Link]
Examples
>>> G = [Link]()
>>> G.add_edge(1, 2)
>>> G.add_edge(2, 3)
>>> [Link]()
OutEdgeView([(1, 2), (2, 3)])
2.4 Filters
Note: Filters can be used with views to restrict the view (or expand it). They can filter nodes or filter edges. These
examples are intended to help you build new ones. They may instead contain all the filters you ever need.
no_filter(*items)
hide_nodes(nodes)
hide_edges(edges)
hide_diedges(edges)
hide_multidiedges(edges)
hide_multiedges(edges)
show_nodes(nodes)
show_edges(edges)
show_diedges(edges)
show_multidiedges(edges)
show_multiedges(edges)
2.4.1 [Link].no_filter
no_filter(*items)
2.4.2 [Link].hide_nodes
hide_nodes(nodes)
2.4.3 [Link].hide_edges
hide_edges(edges)
2.4.4 [Link].hide_diedges
hide_diedges(edges)
2.4.5 [Link].hide_multidiedges
hide_multidiedges(edges)
2.4.6 [Link].hide_multiedges
hide_multiedges(edges)
2.4.7 [Link].show_nodes
class show_nodes(nodes)
__init__(nodes)
Initialize self. See help(type(self)) for accurate signature.
Methods
2.4.8 [Link].show_edges
show_edges(edges)
2.4.9 [Link].show_diedges
show_diedges(edges)
2.4.10 [Link].show_multidiedges
show_multidiedges(edges)
2.4.11 [Link].show_multiedges
show_multiedges(edges)
THREE
ALGORITHMS
3.1.1 Connectivity
[Link].all_pairs_node_connectivity
141
NetworkX Reference, Release 2.5
References
[Link].local_node_connectivity
Examples
1 White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
[Link]
Notes
This algorithm1 finds node independents paths between two nodes by computing their shortest path using BFS,
marking the nodes of the path found as ‘used’ and then searching other shortest paths excluding the nodes
marked as used until no more paths exist. It is not exact because a shortest path could use nodes that, if the path
were longer, may belong to two different node independent paths. Thus it only guarantees an strict lower bound
on node connectivity.
Note that the authors propose a further refinement, losing accuracy and gaining speed, which is not implemented
yet.
See also:
all_pairs_node_connectivity(), node_connectivity()
References
[Link].node_connectivity
Examples
1 White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
[Link]
Notes
This algorithm1 finds node independents paths between two nodes by computing their shortest path using BFS,
marking the nodes of the path found as ‘used’ and then searching other shortest paths excluding the nodes
marked as used until no more paths exist. It is not exact because a shortest path could use nodes that, if the path
were longer, may belong to two different node independent paths. Thus it only guarantees an strict lower bound
on node connectivity.
See also:
all_pairs_node_connectivity(), local_node_connectivity()
References
3.1.2 K-components
[Link].k_components
k_components(G, min_density=0.95)
Returns the approximate k-component structure of a graph G.
A k-component is a maximal subgraph of a graph G that has, at least, node connectivity k: we need to remove at
least k nodes to break it into more components. k-components have an inherent hierarchical structure because
they are nested in terms of connectivity: a connected graph can contain several 2-components, each of which
can contain one or more 3-components, and so forth.
This implementation is based on the fast heuristics to approximate the k-component structure of a graph1 .
Which, in turn, it is based on a fast approximation algorithm for finding good lower bounds of the number of
node independent paths between two nodes2 .
Parameters
• G (NetworkX graph) – Undirected graph
• min_density (Float) – Density relaxation threshold. Default value 0.95
Returns k_components – Dictionary with connectivity level k as key and a list of sets of nodes that
form a k-component of level k as values.
Return type dict
1 Torrents, J. and F. Ferraro (2015) Structural Cohesion: Visualization and Heuristics for Fast Computation. [Link]
2 White, Douglas R., and Mark Newman (2001) A Fast Algorithm for Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
[Link]
Examples
Notes
The logic of the approximation algorithm for computing the k-component structure1 is based on repeatedly
applying simple and fast algorithms for k-cores and biconnected components in order to narrow down the
number of pairs of nodes over which we have to compute White and Newman’s approximation algorithm for
finding node independent paths2 . More formally, this algorithm is based on Whitney’s theorem, which states
an inclusion relation among node connectivity, edge connectivity, and minimum degree for any graph G. This
theorem implies that every k-component is nested inside a k-edge-component, which in turn, is contained in a
k-core. Thus, this algorithm computes node independent paths among pairs of nodes in each biconnected part
of each k-core, and repeats this procedure for each k from 3 to the maximal core number of a node in the input
graph.
Because, in practice, many nodes of the core of level k inside a bicomponent actually are part of a component
of level k, the auxiliary graph needed for the algorithm is likely to be very dense. Thus, we use a complement
graph data structure (see AntiGraph) to save memory. AntiGraph only stores information of the edges that
are not present in the actual auxiliary graph. When applying algorithms to this complement graph data structure,
it behaves as if it were the dense version.
See also:
k_components()
References
3.1.3 Clique
[Link].max_clique
max_clique(G)
Find the Maximum Clique
Finds the 𝑂(|𝑉 |/(𝑙𝑜𝑔|𝑉 |)2 ) apx of maximum clique/independent set in the worst case.
Parameters G (NetworkX graph) – Undirected graph
Returns clique – The apx-maximum clique of the graph
Return type set
Notes
A clique in an undirected graph G = (V, E) is a subset of the vertex set C subseteq V such that for every two
vertices in C there exists an edge connecting the two. This is equivalent to saying that the subgraph induced by
C is complete (in some cases, the term clique may also refer to the subgraph).
A maximum clique is a clique of the largest possible size in a given graph. The clique number omega(G) of
a graph G is the number of vertices in a maximum clique in G. The intersection number of G is the smallest
number of cliques that together cover all edges of G.
[Link]
References
[Link].clique_removal
clique_removal(G)
Repeatedly remove cliques from the graph.
Results in a 𝑂(|𝑉 |/(log |𝑉 |)2 ) approximation of maximum clique and independent set. Returns the largest
independent set found, along with found maximal cliques.
Parameters G (NetworkX graph) – Undirected graph
Returns max_ind_cliques – 2-tuple of Maximal Independent Set and list of maximal cliques (sets).
Return type (set, list) tuple
References
[Link].large_clique_size
large_clique_size(G)
Find the size of a large clique in a graph.
A clique is a subset of nodes in which each pair of nodes is adjacent. This function is a heuristic for finding the
size of a large clique in the graph.
Parameters G (NetworkX graph)
Returns The size of a large clique in the graph.
Return type int
Notes
This implementation is from1 . Its worst case time complexity is 𝑂(𝑛𝑑2 ), where n is the number of nodes in the
graph and d is the maximum degree.
This function is a heuristic, which means it may work well in practice, but there is no rigorous mathematical
guarantee on the ratio between the returned number and the actual largest clique size in the graph.
1
Pattabiraman, Bharath, et al. “Fast Algorithms for the Maximum Clique Problem on Massive Graphs with Applications to Overlapping
Community Detection.” Internet Mathematics 11.4-5 (2015): 421–448. <[Link]
References
See also:
3.1.4 Clustering
[Link].clustering_coefficient.average_clustering
References
2004. [Link]
[Link].dominating_set.min_weighted_dominating_set
min_weighted_dominating_set(G, weight=None)
Returns a dominating set that approximates the minimum weight node dominating set.
Parameters
• G (NetworkX graph) – Undirected graph.
• weight (string) – The node attribute storing the weight of an node. If provided, the node
attribute with this key must be a number for each node. If not provided, each node is assumed
to have weight one.
Returns min_weight_dominating_set – A set of nodes, the sum of whose weights is no more than
(log w(V)) w(V^*), where w(V) denotes the sum of the weights of each node in the graph
and w(V^*) denotes the sum of the weights of each node in the minimum weight dominating
set.
Return type set
Notes
This algorithm computes an approximate minimum weighted dominating set for the graph G. The returned
solution has weight (log w(V)) w(V^*), where w(V) denotes the sum of the weights of each node in the
graph and w(V^*) denotes the sum of the weights of each node in the minimum weight dominating set for the
graph.
This implementation of the algorithm runs in 𝑂(𝑚) time, where 𝑚 is the number of edges in the graph.
References
[Link].dominating_set.min_edge_dominating_set
min_edge_dominating_set(G)
Returns minimum cardinality edge dominating set.
Parameters G (NetworkX graph) – Undirected graph
Returns min_edge_dominating_set – Returns a set of dominating edges whose size is no more
than 2 * OPT.
Return type set
Notes
The algorithm computes an approximate solution to the edge dominating set problem. The result is no more
than 2 * OPT in terms of size of the set. Runtime of the algorithm is 𝑂(|𝐸|).
Independent Set
Independent set or stable set is a set of vertices in a graph, no two of which are adjacent. That is, it is a set I of vertices
such that for every two vertices in I, there is no edge connecting the two. Equivalently, each edge in the graph has at
most one endpoint in I. The size of an independent set is the number of vertices it contains.
A maximum independent set is a largest independent set for a given graph G and its size is denoted 𝛼(𝐺). The problem
of finding such a set is called the maximum independent set problem and is an NP-hard optimization problem. As
such, it is unlikely that there exists an efficient algorithm for finding a maximum independent set of a graph.
Wikipedia: Independent set
Independent set algorithm is based on the following paper:
𝑂(|𝑉 |/(𝑙𝑜𝑔|𝑉 |)2 ) apx of maximum clique/independent set.
Boppana, R., & Halldórsson, M. M. (1992). Approximating maximum independent sets by excluding subgraphs. BIT
Numerical Mathematics, 32(2), 180–196. Springer. doi:10.1007/BF01994876
[Link].independent_set.maximum_independent_set
maximum_independent_set(G)
Returns an approximate maximum independent set.
Parameters G (NetworkX graph) – Undirected graph
Returns iset – The apx-maximum independent set
Return type Set
Notes
Finds the 𝑂(|𝑉 |/(𝑙𝑜𝑔|𝑉 |)2 ) apx of independent set in the worst case.
References
3.1.7 Matching
Graph Matching
Given a graph G = (V,E), a matching M in G is a set of pairwise non-adjacent edges; that is, no two edges share a
common vertex.
Wikipedia: Matching
[Link].min_maximal_matching
min_maximal_matching(G)
Returns the minimum maximal matching of G. That is, out of all maximal matchings of the graph G, the smallest
is returned.
Parameters G (NetworkX graph) – Undirected graph
Returns min_maximal_matching – Returns a set of edges such that no two edges share a common
endpoint and every edge not in the set shares some common endpoint in the set. Cardinality will
be 2*OPT in the worst case.
Return type set
Notes
The algorithm computes an approximate solution fo the minimum maximal cardinality matching problem. The
solution is no more than 2 * OPT in size. Runtime is 𝑂(|𝐸|).
References
3.1.8 Ramsey
Ramsey numbers.
[Link].ramsey_R2
ramsey_R2(G)
Compute the largest clique and largest independent set in G.
This can be used to estimate bounds for the 2-color Ramsey number R(2;s,t) for G.
This is a recursive implementation which could run into trouble for large recursions. Note that self-loop edges
are ignored.
Parameters G (NetworkX graph) – Undirected graph
Returns max_pair – Maximum clique, Maximum independent set.
Return type (set, set) tuple
[Link].metric_closure
metric_closure(G, weight='weight')
Return the metric closure of a graph.
The metric closure of a graph G is the complete graph in which each edge is weighted by the shortest path
distance between the nodes in G .
Parameters G (NetworkX graph)
Returns Metric closure of the graph G.
Return type NetworkX graph
[Link].steiner_tree
Notes
For multigraphs, the edge between two nodes with minimum weight is the edge put into the Steiner tree.
References
3.1.10 Treewidth
The notions of treewidth and tree decomposition have gained their attractiveness partly because many graph and
network problems that are intractable (e.g., NP-hard) on arbitrary graphs become efficiently solvable (e.g., with a
linear time algorithm) when the treewidth of the input graphs is bounded by a constant12 .
There are two different functions for computing a tree decomposition: treewidth_min_degree() and
treewidth_min_fill_in().
[Link].treewidth_min_degree
treewidth_min_degree(G)
Returns a treewidth decomposition using the Minimum Degree heuristic.
The heuristic chooses the nodes according to their degree, i.e., first the node with the lowest degree is chosen,
then the graph is updated and the corresponding node is removed. Next, a new node with the lowest degree is
chosen, and so on.
Parameters G (NetworkX graph)
Returns Treewidth decomposition – 2-tuple with treewidth and the corresponding decomposed
tree.
Return type (int, Graph) tuple
[Link].treewidth_min_fill_in
treewidth_min_fill_in(G)
Returns a treewidth decomposition using the Minimum Fill-in heuristic.
The heuristic chooses a node from the graph, where the number of edges added turning the neighbourhood of
the chosen node into clique is as small as possible.
Parameters G (NetworkX graph)
Returns Treewidth decomposition – 2-tuple with treewidth and the corresponding decomposed
tree.
Return type (int, Graph) tuple
1 Hans L. Bodlaender and Arie M. C. A. Koster. 2010. “Treewidth computations [Link] bounds”. Inf. Comput. 208, 3 (March 2010),259-275.
[Link]
2 Hans L. Bodlaender. “Discovering Treewidth”. Institute of Information and Computing Sciences, Utrecht University. Technical Report
UU-CS-2005-018. [Link]
[Link].vertex_cover.min_weighted_vertex_cover
min_weighted_vertex_cover(G, weight=None)
Returns an approximate minimum weighted vertex cover.
The set of nodes returned by this function is guaranteed to be a vertex cover, and the total weight of the set is
guaranteed to be at most twice the total weight of the minimum weight vertex cover. In other words,
𝑤(𝑆) ≤ 2 * 𝑤(𝑆 * ),
where 𝑆 is the vertex cover returned by this function, 𝑆 * is the vertex cover of minimum weight out of all vertex
covers of the graph, and 𝑤 is the function that computes the sum of the weights of each node in that given set.
Parameters
• G (NetworkX graph)
• weight (string, optional (default = None)) – If None, every node has weight 1. If a string,
use this node attribute as the node weight. A node without this attribute is assumed to have
weight 1.
Returns min_weighted_cover – Returns a set of nodes whose weight sum is no more than twice
the weight sum of the minimum weight vertex cover.
Return type set
Notes
For a directed graph, a vertex cover has the same definition: a set of nodes such that each edge in the graph is
incident to at least one node in the set. Whether the node is the head or tail of the directed edge is ignored.
This is the local-ratio algorithm for computing an approximate vertex cover. The algorithm greedily reduces
the costs over edges, iteratively building a cover. The worst-case runtime of this implementation is 𝑂(𝑚 log 𝑛),
where 𝑛 is the number of nodes and 𝑚 the number of edges in the graph.
References
3.2 Assortativity
3.2.1 Assortativity
[Link].degree_assortativity_coefficient
Examples
>>> G = nx.path_graph(4)
>>> r = nx.degree_assortativity_coefficient(G)
>>> print(f"{r:3.1f}")
-0.5
See also:
attribute_assortativity_coefficient(), numeric_assortativity_coefficient(),
neighbor_connectivity(), degree_mixing_dict(), degree_mixing_matrix()
Notes
This computes Eq. (21) in Ref.1 , where e is the joint probability distribution (mixing matrix) of the degrees. If
G is directed than the matrix e is the joint probability of the user-specified degree type for the source and target.
References
[Link].attribute_assortativity_coefficient
Examples
>>> G = [Link]()
>>> G.add_nodes_from([0, 1], color="red")
>>> G.add_nodes_from([2, 3], color="blue")
>>> G.add_edges_from([(0, 1), (2, 3)])
>>> print(nx.attribute_assortativity_coefficient(G, "color"))
1.0
Notes
This computes Eq. (2) in Ref.1 , (trace(M)-sum(M^2))/(1-sum(M^2)), where M is the joint probability distribu-
tion (mixing matrix) of the specified attribute.
References
[Link].numeric_assortativity_coefficient
• G (NetworkX graph)
• attribute (string) – Node attribute key. The corresponding attribute value must be an integer.
• nodes (list or iterable (optional)) – Compute numeric assortativity only for attributes of
nodes in container. The default is all nodes.
Returns r – Assortativity of graph for given attribute
Return type float
Examples
>>> G = [Link]()
>>> G.add_nodes_from([0, 1], size=2)
>>> G.add_nodes_from([2, 3], size=3)
>>> G.add_edges_from([(0, 1), (2, 3)])
>>> print(nx.numeric_assortativity_coefficient(G, "size"))
1.0
Notes
This computes Eq. (21) in Ref.1 , for the mixing matrix of of the specified attribute.
References
[Link].degree_pearson_correlation_coefficient
Examples
>>> G = nx.path_graph(4)
>>> r = nx.degree_pearson_correlation_coefficient(G)
>>> print(f"{r:3.1f}")
-0.5
Notes
References
average_neighbor_degree(G[, source, target, Returns the average degree of the neighborhood of each
. . . ]) node.
[Link].average_neighbor_degree
where N(i) are the neighbors of node i and k_j is the degree of node j which belongs to N(i). For weighted
graphs, an analogous measure can be defined1 ,
𝑤 1 ∑︁
𝑘𝑛𝑛,𝑖 = 𝑤𝑖𝑗 𝑘𝑗
𝑠𝑖
𝑗∈𝑁 (𝑖)
where s_i is the weighted degree of node i, w_{ij} is the weight of the edge that links i and j and N(i)
are the neighbors of node i.
Parameters
• G (NetworkX graph)
• source (string (“in”|”out”)) – Directed graphs only. Use “in”- or “out”-degree for source
node.
• target (string (“in”|”out”)) – Directed graphs only. Use “in”- or “out”-degree for target
node.
• nodes (list or iterable, optional) – Compute neighbor degree for specified nodes. The default
is all nodes in the graph.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1.
1A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani, “The architecture of complex weighted networks”. PNAS 101 (11):
3747–3752 (2004).
Examples
>>> G = nx.path_graph(4)
>>> [Link][0, 1]["weight"] = 5
>>> [Link][2, 3]["weight"] = 3
>>> nx.average_neighbor_degree(G)
{0: 2.0, 1: 1.5, 2: 1.5, 3: 2.0}
>>> nx.average_neighbor_degree(G, weight="weight")
{0: 2.0, 1: 1.1666666666666667, 2: 1.25, 3: 2.0}
>>> G = [Link]()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> nx.average_neighbor_degree(G, source="in", target="in")
{0: 1.0, 1: 1.0, 2: 1.0, 3: 0.0}
Notes
For directed graphs you can also specify in-degree or out-degree by passing keyword arguments.
See also:
average_degree_connectivity()
References
[Link].average_degree_connectivity
3747–3752 (2004).
node i, as
𝑤 1 ∑︁
𝑘𝑛𝑛,𝑖 = 𝑤𝑖𝑗 𝑘𝑗
𝑠𝑖
𝑗∈𝑁 (𝑖)
where s_i is the weighted degree of node i, w_{ij} is the weight of the edge that links i and j, and N(i)
are the neighbors of node i.
Parameters
• G (NetworkX graph)
• source (“in”|”out”|”in+out” (default:”in+out”)) – Directed graphs only. Use “in”- or
“out”-degree for source node.
• target (“in”|”out”|”in+out” (default:”in+out”) – Directed graphs only. Use “in”- or
“out”-degree for target node.
• nodes (list or iterable (optional)) – Compute neighbor connectivity for these nodes. The
default is all nodes.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1.
Returns d – A dictionary keyed by degree k with the value of average connectivity.
Return type dict
Raises ValueError – If either source or target are not one of ‘in’, ‘out’, or ‘in+out’.
Examples
>>> G = nx.path_graph(4)
>>> [Link][1, 2]["weight"] = 3
>>> nx.k_nearest_neighbors(G)
{1: 2.0, 2: 1.5}
>>> nx.k_nearest_neighbors(G, weight="weight")
{1: 2.0, 2: 1.75}
See also:
neighbors_average_degree()
Notes
This algorithm is sometimes called “k nearest neighbors” and is also available as k_nearest_neighbors.
References
[Link].k_nearest_neighbors
node i, as
𝑤 1 ∑︁
𝑘𝑛𝑛,𝑖 = 𝑤𝑖𝑗 𝑘𝑗
𝑠𝑖
𝑗∈𝑁 (𝑖)
where s_i is the weighted degree of node i, w_{ij} is the weight of the edge that links i and j, and N(i)
are the neighbors of node i.
Parameters
• G (NetworkX graph)
• source (“in”|”out”|”in+out” (default:”in+out”)) – Directed graphs only. Use “in”- or
“out”-degree for source node.
• target (“in”|”out”|”in+out” (default:”in+out”) – Directed graphs only. Use “in”- or
“out”-degree for target node.
• nodes (list or iterable (optional)) – Compute neighbor connectivity for these nodes. The
default is all nodes.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1.
Returns d – A dictionary keyed by degree k with the value of average connectivity.
Return type dict
Raises ValueError – If either source or target are not one of ‘in’, ‘out’, or ‘in+out’.
Examples
>>> G = nx.path_graph(4)
>>> [Link][1, 2]["weight"] = 3
>>> nx.k_nearest_neighbors(G)
{1: 2.0, 2: 1.5}
>>> nx.k_nearest_neighbors(G, weight="weight")
{1: 2.0, 2: 1.75}
See also:
neighbors_average_degree()
Notes
This algorithm is sometimes called “k nearest neighbors” and is also available as k_nearest_neighbors.
References
3.2.4 Mixing
[Link].attribute_mixing_matrix
[Link].degree_mixing_matrix
[Link].numeric_mixing_matrix
[Link].attribute_mixing_dict
Examples
>>> G = [Link]()
>>> G.add_nodes_from([0, 1], color="red")
>>> G.add_nodes_from([2, 3], color="blue")
>>> G.add_edge(1, 3)
>>> d = nx.attribute_mixing_dict(G, "color")
>>> print(d["red"]["blue"])
1
>>> print(d["blue"]["red"]) # d symmetric for undirected graphs
1
[Link].degree_mixing_dict
[Link].mixing_dict
mixing_dict(xy, normalized=False)
Returns a dictionary representation of mixing matrix.
Parameters
• xy (list or container of two-tuples) – Pairs of (x,y) items.
• attribute (string) – Node attribute key
• normalized (bool (default=False)) – Return counts if False or probabilities if True.
Returns d – Counts or Joint probability of occurrence of values in xy.
Return type dictionary
3.2.5 Pairs
node_attribute_xy(G, attribute[, nodes]) Returns iterator of node-attribute pairs for all edges in
G.
node_degree_xy(G[, x, y, weight, nodes]) Generate node degree-degree pairs for edges in G.
[Link].node_attribute_xy
Examples
>>> G = [Link]()
>>> G.add_node(1, color="red")
>>> G.add_node(2, color="blue")
>>> G.add_edge(1, 2)
>>> list(nx.node_attribute_xy(G, "color"))
[('red', 'blue')]
Notes
For undirected graphs each edge is produced twice, once for each edge representation (u,v) and (v,u), with the
exception of self-loop edges which only appear once.
[Link].node_degree_xy
Examples
>>> G = [Link]()
>>> G.add_edge(1, 2)
>>> list(nx.node_degree_xy(G, x="out", y="in"))
[(1, 1)]
>>> list(nx.node_degree_xy(G, x="in", y="out"))
[(0, 0)]
Notes
For undirected graphs each edge is produced twice, once for each edge representation (u,v) and (v,u), with the
exception of self-loop edges which only appear once.
3.3 Asteroidal
3.3.1 [Link].is_at_free
is_at_free(G)
Check if a graph is AT-free.
The method uses the find_asteroidal_triple method to recognize an AT-free graph. If no asteroidal
triple is found the graph is AT-free and True is returned. If at least one asteroidal triple is found the graph is not
AT-free and False is returned.
Parameters G (NetworkX Graph) – The graph to check whether is AT-free or not.
Returns True if G is AT-free and False otherwise.
Return type bool
Examples
>>> G = [Link]([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)])
>>> nx.is_at_free(G)
True
>>> G = nx.cycle_graph(6)
>>> nx.is_at_free(G)
False
3.3.2 [Link].find_asteroidal_triple
find_asteroidal_triple(G)
Find an asteroidal triple in the given graph.
An asteroidal triple is a triple of non-adjacent vertices such that there exists a path between any two of them
which avoids the closed neighborhood of the third. It checks all independent triples of vertices and whether
they are an asteroidal triple or not. This is done with the help of a data structure called a component structure.
A component structure encodes information about which vertices belongs to the same connected component
when the closed neighborhood of a given vertex is removed from the graph. The algorithm used to check is the
trivial one, outlined in1 , which has a runtime of 𝑂(|𝑉 ||𝐸 + |𝑉 ||𝐸|), where the second term is the creation of
the component structure.
Parameters G (NetworkX Graph) – The graph to check whether is AT-free or not
Returns An asteroidal triple is returned as a list of nodes. If no asteroidal triple exists, i.e. the graph
is AT-free, then None is returned. The returned value depends on the certificate parameter. The
default option is a bool which is True if the graph is AT-free, i.e. the given graph contains no
asteroidal triples, and False otherwise, i.e. if the graph contains at least one asteroidal triple.
Return type list or None
Notes
The component structure and the algorithm is described in1 . The current implementation implements the trivial
algorithm for simple graphs.
References
3.4 Bipartite
This module provides functions and operations for bipartite graphs. Bipartite graphs B = (U, V, E) have two
node sets U,V and edges in E that only connect nodes from opposite sets. It is common in the literature to use an
spatial analogy referring to the two node sets as top and bottom nodes.
The bipartite algorithms are not imported into the networkx namespace at the top level so the easiest way to use them
is with:
NetworkX does not have a custom bipartite graph class but the Graph() or DiGraph() classes can be used to represent
bipartite graphs. However, you have to keep track of which set each node belongs to, and make sure that there is no
edge between nodes of the same set. The convention used in NetworkX is to use a node attribute named bipartite
with values 0 or 1 to identify the sets each node belongs to. This convention is not enforced in the source code of
bipartite functions, it’s only a recommendation.
For example:
>>> B = [Link]()
>>> # Add nodes with the node attribute "bipartite"
>>> B.add_nodes_from([1, 2, 3, 4], bipartite=0)
>>> B.add_nodes_from(["a", "b", "c"], bipartite=1)
(continues on next page)
1 Ekkehard Köhler, “Recognizing Graphs without asteroidal triples”, Journal of Discrete Algorithms 2, pages 439-452, 2004. [Link]
[Link]/science/article/pii/S157086670400019X
Many algorithms of the bipartite module of NetworkX require, as an argument, a container with all the nodes that
belong to one set, in addition to the bipartite graph B. The functions in the bipartite package do not check that the node
set is actually correct nor that the input graph is actually bipartite. If B is connected, you can find the two node sets
using a two-coloring algorithm:
>>> nx.is_connected(B)
True
>>> bottom_nodes, top_nodes = [Link](B)
However, if the input graph is not connected, there are more than one possible colorations. This is the reason why we
require the user to pass a container with all nodes of one bipartite node set as an argument to most bipartite functions.
In the face of ambiguity, we refuse the temptation to guess and raise an AmbiguousSolution Exception if the
input graph for [Link] is disconnected.
Using the bipartite node attribute, you can easily get the two node sets:
So you can easily use the bipartite algorithms that require, as an argument, a container with all nodes that belong to
one node set:
All bipartite graph generators in NetworkX build bipartite graphs with the bipartite node attribute. Thus, you can
use the same approach:
[Link].is_bipartite
is_bipartite(G)
Returns True if graph G is bipartite, False if not.
Parameters G (NetworkX graph)
Examples
See also:
color(), is_bipartite_node_set()
[Link].is_bipartite_node_set
is_bipartite_node_set(G, nodes)
Returns True if nodes and G/nodes are a bipartition of G.
Parameters
• G (NetworkX graph)
• nodes (list or container) – Check if nodes are a one of a bipartite set.
Examples
Notes
For connected graphs the bipartite sets are unique. This function handles disconnected graphs.
[Link]
sets(G, top_nodes=None)
Returns bipartite node sets of graph G.
Raises an exception if the graph is not bipartite or if the input graph is disconnected and thus more than one valid
solution exists. See bipartite documentation for further details on how bipartite graphs are handled in
NetworkX.
Parameters
• G (NetworkX graph)
• top_nodes (container, optional) – Container with all nodes in one bipartite node set. If not
supplied it will be computed. But if more than one solution exists an exception will be
raised.
Returns
• X (set) – Nodes from one side of the bipartite graph.
• Y (set) – Nodes from the other side.
Raises
• AmbiguousSolution – Raised if the input bipartite graph is disconnected and no con-
tainer with all nodes in one bipartite set is provided. When determining the nodes in each
bipartite set more than one valid solution is possible if the input graph is disconnected.
• NetworkXError – Raised if the input graph is not bipartite.
Examples
See also:
color()
[Link]
color(G)
Returns a two-coloring of the graph.
Raises an exception if the graph is not bipartite.
Parameters G (NetworkX graph)
Returns color – A dictionary keyed by node with a 1 or 0 as data for each node color.
Return type dictionary
Raises NetworkXError – If the graph is not two-colorable.
Examples
You can use this to set a node attribute indicating the biparite set:
[Link]
density(B, nodes)
Returns density of bipartite graph B.
Parameters
• G (NetworkX graph)
• nodes (list or container) – Nodes in one node set of the bipartite graph.
Returns d – The bipartite density
Return type float
Examples
Notes
The container of nodes passed as argument must contain all nodes in one of the two bipartite node sets to avoid
ambiguity in the case of disconnected graphs. See bipartite documentation for further details on how
bipartite graphs are handled in NetworkX.
See also:
color()
[Link]
Examples
Notes
The container of nodes passed as argument must contain all nodes in one of the two bipartite node sets to avoid
ambiguity in the case of disconnected graphs. See bipartite documentation for further details on how
bipartite graphs are handled in NetworkX.
See also:
color(), density()
3.4.2 Edgelist
Format
You can read or write three formats of edge lists with these functions.
Node pairs with no data:
1 2
1 2 {'weight':7, 'color':'green'}
Arbitrary data:
1 2 7 green
For each edge (u, v) the node u is assigned to part 0 and the node v to part 1.
generate_edgelist(G[, delimiter, data]) Generate a single line of the bipartite graph G in edge
list format.
write_edgelist(G, path[, comments, . . . ]) Write a bipartite graph as a list of edges.
parse_edgelist(lines[, comments, delimiter, . . . ]) Parse lines of an edge list representation of a bipartite
graph.
read_edgelist(path[, comments, delimiter, . . . ]) Read a bipartite graph from a list of edges.
[Link].generate_edgelist
Examples
[Link].write_edgelist
Examples
>>> G = nx.path_graph(4)
>>> G.add_nodes_from([0, 2], bipartite=0)
>>> G.add_nodes_from([1, 3], bipartite=1)
>>> nx.write_edgelist(G, "[Link]")
>>> fh = open("[Link]", "wb")
>>> nx.write_edgelist(G, fh)
>>> nx.write_edgelist(G, "[Link]")
>>> nx.write_edgelist(G, "[Link]", data=False)
>>> G = [Link]()
>>> G.add_edge(1, 2, weight=7, color="red")
>>> nx.write_edgelist(G, "[Link]", data=False)
>>> nx.write_edgelist(G, "[Link]", data=["color"])
>>> nx.write_edgelist(G, "[Link]", data=["color", "weight"])
See also:
write_edgelist(), generate_edgelist()
[Link].parse_edgelist
Examples
>>> sorted([Link]())
[(1, 2), (2, 3), (3, 4)]
[Link].read_edgelist
Examples
Notes
Since nodes must be hashable, the function nodetype must return hashable types (e.g. int, float, str, frozenset -
or tuples of those, etc.)
3.4.3 Matching
Provides functions for computing maximum cardinality matchings and minimum weight full matchings in a bipartite
graph.
If you don’t care about the particular implementation of the maximum matching algorithm, simply use the
maximum_matching(). If you do care, you can import one of the named maximum matching algorithms directly.
For example, to find a maximum matching in the complete bipartite graph with two vertices on the left and three
vertices on the right:
>>> G = nx.complete_bipartite_graph(2, 3)
>>> left, right = [Link](G)
>>> list(left)
[0, 1]
>>> list(right)
[2, 3, 4]
>>> [Link].maximum_matching(G)
{0: 2, 1: 3, 2: 0, 3: 1}
The dictionary returned by maximum_matching() includes a mapping for vertices in both the left and right vertex
sets.
Similarly, minimum_weight_full_matching() produces, for a complete weighted bipartite graph, a matching
whose cardinality is the cardinality of the smaller of the two partitions, and for which the sum of the weights of the
edges included in the matching is minimal.
[Link].eppstein_matching
eppstein_matching(G, top_nodes=None)
Returns the maximum cardinality matching of the bipartite graph G.
Parameters
• G (NetworkX graph) – Undirected bipartite graph
• top_nodes (container) – Container with all nodes in one bipartite node set. If not supplied
it will be computed. But if more than one solution exists an exception will be raised.
Returns matches – The matching is returned as a dictionary, matching, such that matching[v]
== w if node v is matched to node w. Unmatched nodes do not occur as a key in matching.
Return type dictionary
Raises AmbiguousSolution – Raised if the input bipartite graph is disconnected and no con-
tainer with all nodes in one bipartite set is provided. When determining the nodes in each
bipartite set more than one valid solution is possible if the input graph is disconnected.
Notes
This function is implemented with David Eppstein’s version of the algorithm Hopcroft–Karp algorithm (see
hopcroft_karp_matching()), which originally appeared in the Python Algorithms and Data Structures
library (PADS).
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
hopcroft_karp_matching()
[Link].hopcroft_karp_matching
hopcroft_karp_matching(G, top_nodes=None)
Returns the maximum cardinality matching of the bipartite graph G.
A matching is a set of edges that do not share any nodes. A maximum cardinality matching is a matching with
the most edges possible. It is not always unique. Finding a matching in a bipartite graph can be treated as a
networkx flow problem.
The functions hopcroft_karp_matching and maximum_matching are aliases of the same function.
Parameters
• G (NetworkX graph) – Undirected bipartite graph
• top_nodes (container of nodes) – Container with all nodes in one bipartite node set. If not
supplied it will be computed. But if more than one solution exists an exception will be
raised.
Returns matches – The matching is returned as a dictionary, matches, such that matches[v]
== w if node v is matched to node w. Unmatched nodes do not occur as a key in matches.
Return type dictionary
Raises AmbiguousSolution – Raised if the input bipartite graph is disconnected and no con-
tainer with all nodes in one bipartite set is provided. When determining the nodes in each
bipartite set more than one valid solution is possible if the input graph is disconnected.
Notes
This function is implemented with the Hopcroft–Karp matching algorithm for bipartite graphs.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
maximum_matching(), hopcroft_karp_matching(), eppstein_matching()
References
[Link].to_vertex_cover
Notes
This function is implemented using the procedure guaranteed by Konig’s theorem, which proves an equivalence
between a maximum matching and a minimum vertex cover in bipartite graphs.
Since a minimum vertex cover is the complement of a maximum independent set for any graph, one can compute
the maximum independent set of a bipartite graph this way:
>>> G = nx.complete_bipartite_graph(2, 3)
>>> matching = [Link].maximum_matching(G)
>>> vertex_cover = [Link].to_vertex_cover(G, matching)
>>> independent_set = set(G) - vertex_cover
>>> print(list(independent_set))
[2, 3, 4]
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
[Link].maximum_matching
maximum_matching(G, top_nodes=None)
Returns the maximum cardinality matching in the given bipartite graph.
This function is simply an alias for hopcroft_karp_matching().
[Link].minimum_weight_full_matching
|𝑀 | = min(|𝑈 |, |𝑉 |),
∑︀
which minimizes the sum of the weights of the edges included in the matching, 𝑒∈𝑀 𝑤(𝑒), or raises an error
if no such matching exists.
When |𝑈 | = |𝑉 |, this is commonly referred to as a perfect matching; here, since we allow |𝑈 | and |𝑉 | to differ,
we follow Karp1 and refer to the matching as full.
Parameters
• G (NetworkX graph) – Undirected bipartite graph
• top_nodes (container) – Container with all nodes in one bipartite node set. If not supplied
it will be computed.
• weight (string, optional (default=’weight’)) – The edge data key used to provide each value
in the matrix.
Returns matches – The matching is returned as a dictionary, matches, such that matches[v]
== w if node v is matched to node w. Unmatched nodes do not occur as a key in matches.
Return type dictionary
Raises
• ValueError – Raised if no full matching exists.
• ImportError – Raised if SciPy is not available.
Notes
The problem of determining a minimum weight full matching is also known as the rectangular linear assignment
problem. This implementation defers the calculation of the assignment to SciPy.
1 Richard Manning Karp: An algorithm to Solve the m x n Assignment Problem in Expected Time O(mn log n). Networks, 10(2):143–152,
1980.
References
3.4.4 Matrix
Biadjacency matrices
[Link].biadjacency_matrix
Notes
References
[Link].from_biadjacency_matrix
Notes
The nodes are labeled with the attribute bipartite set to an integer 0 or 1 representing membership in part 0
or part 1 of the bipartite graph.
If create_using is an instance of [Link] or [Link] and the
entries of A are of type int, then this function returns a multigraph (of the same type as create_using)
with parallel edges. In this case, edge_attribute will be ignored.
See also:
biadjacency_matrix(), from_numpy_array()
References
[1] [Link]
3.4.5 Projections
projected_graph(B, nodes[, multigraph])Returns the projection of B onto one of its node sets.
weighted_projected_graph(B, nodes[, ratio])
Returns a weighted projection of B onto one of its node
sets.
Newman’s weighted projection of B onto one of its node
collaboration_weighted_projected_graph(B,
nodes) sets.
overlap_weighted_projected_graph(B, Overlap weighted projection of B onto one of its node
nodes[, . . . ]) sets.
generic_weighted_projected_graph(B, Weighted projection of B with a user-specified weight
nodes[, . . . ]) function.
[Link].projected_graph
Examples
If nodes a, and b are connected through both nodes 1 and 2 then building a multigraph results in two edges in
the projection onto [a, b]:
>>> B = [Link]()
>>> B.add_edges_from([("a", 1), ("b", 1), ("a", 2), ("b", 2)])
>>> G = bipartite.projected_graph(B, ["a", "b"], multigraph=True)
>>> print([sorted((u, v)) for u, v in [Link]()])
[['a', 'b'], ['a', 'b']]
Notes
No attempt is made to verify that the input graph B is bipartite. Returns a simple graph that is the projection of
the bipartite graph B onto the set of nodes given in list nodes. If multigraph=True then a multigraph is returned
with an edge for every shared neighbor.
Directed graphs are allowed as input. The output will also then be a directed graph with edges if there is a
directed path between the nodes.
The graph and node properties are (shallow) copied to the projected graph.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
is_bipartite(), is_bipartite_node_set(), sets(), weighted_projected_graph(),
collaboration_weighted_projected_graph(), overlap_weighted_projected_graph(),
generic_weighted_projected_graph()
[Link].weighted_projected_graph
Examples
Notes
No attempt is made to verify that the input graph B is bipartite. The graph and node properties are (shallow)
copied to the projected graph.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
is_bipartite(), is_bipartite_node_set(), sets(), collaboration_weighted_projected_graph(),
overlap_weighted_projected_graph(), generic_weighted_projected_graph(),
projected_graph()
1 Borgatti, S.P. and Halgin, D. In press. “Analyzing Affiliation Networks”. In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social
References
[Link].collaboration_weighted_projected_graph
collaboration_weighted_projected_graph(B, nodes)
Newman’s weighted projection of B onto one of its node sets.
The collaboration weighted projection is the projection of the bipartite network B onto the specified nodes with
weights assigned using Newman’s collaboration model1 :
∑︁ 𝛿 𝑘 𝛿 𝑘
𝑢 𝑣
𝑤𝑢,𝑣 =
𝑑𝑘 − 1
𝑘
where u and v are nodes from the bottom bipartite node set, and k is a node of the top node set. The value d_k
is the degree of node k in the bipartite network and delta_{u}^{k} is 1 if node u is linked to node k in the
original bipartite graph or 0 otherwise.
The nodes retain their attributes and are connected in the resulting graph if have an edge to a common node in
the original bipartite graph.
Parameters
• B (NetworkX graph) – The input graph should be bipartite.
• nodes (list or iterable) – Nodes to project onto (the “bottom” nodes).
Returns Graph – A graph that is the projection onto the given nodes.
Return type NetworkX graph
Examples
Notes
No attempt is made to verify that the input graph B is bipartite. The graph and node properties are (shallow)
copied to the projected graph.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
1 Scientific collaboration networks: II. Shortest paths, weighted networks, and centrality, M. E. J. Newman, Phys. Rev. E 64, 016132 (2001).
References
[Link].overlap_weighted_projected_graph
or if the parameter ‘jaccard’ is False, the fraction of common neighbors by minimum of both nodes degree in
the original bipartite graph1 :
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑤𝑣,𝑢 =
𝑚𝑖𝑛(|𝑁 (𝑢)|, |𝑁 (𝑣)|)
The nodes retain their attributes and are connected in the resulting graph if have an edge to a common node in
the original bipartite graph.
Parameters
• B (NetworkX graph) – The input graph should be bipartite.
• nodes (list or iterable) – Nodes to project onto (the “bottom” nodes).
• jaccard (Bool (default=True))
Returns Graph – A graph that is the projection onto the given nodes.
Return type NetworkX graph
Examples
1 Borgatti, S.P. and Halgin, D. In press. Analyzing Affiliation Networks. In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social
Notes
No attempt is made to verify that the input graph B is bipartite. The graph and node properties are (shallow)
copied to the projected graph.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
is_bipartite(), is_bipartite_node_set(), sets(), weighted_projected_graph(),
collaboration_weighted_projected_graph(), generic_weighted_projected_graph(),
projected_graph()
References
[Link].generic_weighted_projected_graph
Examples
Notes
No attempt is made to verify that the input graph B is bipartite. The graph and node properties are (shallow)
copied to the projected graph.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
is_bipartite(), is_bipartite_node_set(), sets(), weighted_projected_graph(),
collaboration_weighted_projected_graph(), overlap_weighted_projected_graph(),
projected_graph()
3.4.6 Spectral
[Link].spectral_bipartivity
Examples
Notes
This implementation uses Numpy (dense) matrices which are not efficient for storing large sparse graphs.
See also:
color()
References
3.4.7 Clustering
[Link]
where N(N(u)) are the second order neighbors of u in G excluding u, and c_{uv} is the pairwise clustering
coefficient between nodes u and v.
The mode selects the function for c_{uv} which can be:
dot:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
|𝑁 (𝑢) ∪ 𝑁 (𝑣)|
min:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
𝑚𝑖𝑛(|𝑁 (𝑢)|, |𝑁 (𝑣)|)
max:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
𝑚𝑎𝑥(|𝑁 (𝑢)|, |𝑁 (𝑣)|)
Parameters
• G (graph) – A bipartite graph
• nodes (list or iterable (optional)) – Compute bipartite clustering for these nodes. The default
is all nodes in G.
• mode (string) – The pariwise bipartite clustering method to be used in the computation. It
must be “dot”, “max”, or “min”.
Returns clustering – A dictionary keyed by node with the clustering coefficient value.
Return type dictionary
Examples
See also:
robins_alexander_clustering(), square_clustering(), average_clustering()
1 Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008). Basic notions for the analysis of large two-mode networks. Social
References
[Link].average_clustering
Examples
See also:
clustering()
1Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008). Basic notions for the analysis of large two-mode networks. Social
Networks 30(1), 31–48.
Notes
The container of nodes passed to this function must contain all of the nodes in one of the bipartite sets
(“top” or “bottom”) in order to compute the correct average bipartite clustering coefficients. See bipartite
documentation for further details on how bipartite graphs are handled in NetworkX.
References
[Link].latapy_clustering
where N(N(u)) are the second order neighbors of u in G excluding u, and c_{uv} is the pairwise clustering
coefficient between nodes u and v.
The mode selects the function for c_{uv} which can be:
dot:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
|𝑁 (𝑢) ∪ 𝑁 (𝑣)|
min:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
𝑚𝑖𝑛(|𝑁 (𝑢)|, |𝑁 (𝑣)|)
max:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
𝑚𝑎𝑥(|𝑁 (𝑢)|, |𝑁 (𝑣)|)
Parameters
• G (graph) – A bipartite graph
• nodes (list or iterable (optional)) – Compute bipartite clustering for these nodes. The default
is all nodes in G.
• mode (string) – The pariwise bipartite clustering method to be used in the computation. It
must be “dot”, “max”, or “min”.
Returns clustering – A dictionary keyed by node with the clustering coefficient value.
Return type dictionary
1 Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008). Basic notions for the analysis of large two-mode networks. Social
Examples
See also:
robins_alexander_clustering(), square_clustering(), average_clustering()
References
[Link].robins_alexander_clustering
robins_alexander_clustering(G)
Compute the bipartite clustering of G.
Robins and Alexander1 defined bipartite clustering coefficient as four times the number of four cycles C_4
divided by the number of three paths L_3 in a bipartite graph:
4 * 𝐶4
𝐶𝐶4 =
𝐿3
Parameters G (graph) – a bipartite graph
Returns clustering – The Robins and Alexander bipartite clustering for the input graph.
Return type float
Examples
See also:
latapy_clustering(), square_clustering()
1 Robins, G. and M. Alexander (2004). Small worlds among interlocking directors: Network structure and distance in bipartite graphs. Compu-
tational & Mathematical Organization Theory 10(1), 69–94.
References
3.4.8 Redundancy
[Link].node_redundancy
node_redundancy(G, nodes=None)
Computes the node redundancy coefficients for the nodes in the bipartite graph G.
The redundancy coefficient of a node v is the fraction of pairs of neighbors of v that are both linked to other
nodes. In a one-mode projection these nodes would be linked together even if v were not there.
More formally, for any vertex v, the redundancy coefficient of `v` is defined by
Examples
Raises NetworkXError – If any of the nodes in the graph (or in nodes, if specified) has (out-
)degree less than two (which would result in division by zero, according to the definition of the
redundancy coefficient).
References
3.4.9 Centrality
closeness_centrality(G, nodes[, normalized]) Compute the closeness centrality for nodes in a bipartite
network.
degree_centrality(G, nodes) Compute the degree centrality for nodes in a bipartite
network.
betweenness_centrality(G, nodes) Compute betweenness centrality for nodes in a bipartite
network.
[Link].closeness_centrality
Notes
The nodes input parameter must contain all nodes in one bipartite node set, but the dictionary returned contains
all nodes from both node sets. See bipartite documentation for further details on how bipartite graphs
are handled in NetworkX.
Closeness centrality is normalized by the minimum distance possible. In the bipartite case the minimum distance
for a node in one bipartite node set is 1 from all nodes in the other node set and 2 from all other nodes in its own
set1 . Thus the closeness centrality for node v in the two bipartite sets U with n nodes and V with m nodes is
𝑚 + 2(𝑛 − 1)
𝑐𝑣 = , for𝑣 ∈ 𝑈,
𝑑
𝑛 + 2(𝑚 − 1)
𝑐𝑣 = , for𝑣 ∈ 𝑉,
𝑑
where d is the sum of the distances from v to all other nodes.
Higher values of closeness indicate higher centrality.
As in the unipartite case, setting normalized=True causes the values to normalized further to n-1 / size(G)-1
where n is the number of nodes in the connected part of graph containing the node. If the graph is not completely
connected, this algorithm computes the closeness centrality for each connected part separately.
References
[Link].degree_centrality
degree_centrality(G, nodes)
Compute the degree centrality for nodes in a bipartite network.
The degree centrality for a node v is the fraction of nodes connected to it.
Parameters
• G (graph) – A bipartite network
• nodes (list or container) – Container with all nodes in one bipartite node set.
Returns centrality – Dictionary keyed by node with bipartite degree centrality as the value.
Return type dictionary
See also:
betweenness_centrality(), closeness_centrality(), sets(), is_bipartite()
Notes
The nodes input parameter must contain all nodes in one bipartite node set, but the dictionary returned con-
tains all nodes from both bipartite node sets. See bipartite documentation for further details on how
bipartite graphs are handled in NetworkX.
For unipartite networks, the degree centrality values are normalized by dividing by the maximum possible degree
(which is n-1 where n is the number of nodes in G).
1 Borgatti, S.P. and Halgin, D. In press. “Analyzing Affiliation Networks”. In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social
In the bipartite case, the maximum possible degree of a node in a bipartite node set is the number of nodes in the
opposite node set1 . The degree centrality for a node v in the bipartite sets U with n nodes and V with m nodes is
𝑑𝑒𝑔(𝑣)
𝑑𝑣 = , for𝑣 ∈ 𝑈,
𝑚
𝑑𝑒𝑔(𝑣)
𝑑𝑣 = , for𝑣 ∈ 𝑉,
𝑛
where deg(v) is the degree of node v.
References
[Link].betweenness_centrality
betweenness_centrality(G, nodes)
Compute betweenness centrality for nodes in a bipartite network.
Betweenness centrality of a node v is the sum of the fraction of all-pairs shortest paths that pass through v.
Values of betweenness are normalized by the maximum possible value which for bipartite graphs is limited by
the relative size of the two node sets1 .
Let n be the number of nodes in the node set U and m be the number of nodes in the node set V, then nodes in U
are normalized by dividing by
1 2
[𝑚 (𝑠 + 1)2 + 𝑚(𝑠 + 1)(2𝑡 − 𝑠 − 1) − 𝑡(2𝑠 − 𝑡 + 3)],
2
where
𝑠 = (𝑛 − 1) ÷ 𝑚, 𝑡 = (𝑛 − 1) mod 𝑚,
𝑝 = (𝑚 − 1) ÷ 𝑛, 𝑟 = (𝑚 − 1) mod 𝑛.
Parameters
• G (graph) – A bipartite graph
• nodes (list or container) – Container with all nodes in one bipartite node set.
Returns betweenness – Dictionary keyed by node with bipartite betweenness centrality as the value.
Return type dictionary
See also:
degree_centrality(), closeness_centrality(), sets(), is_bipartite()
1 Borgatti, S.P. and Halgin, D. In press. “Analyzing Affiliation Networks”. In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social
Notes
The nodes input parameter must contain all nodes in one bipartite node set, but the dictionary returned contains
all nodes from both node sets. See bipartite documentation for further details on how bipartite graphs
are handled in NetworkX.
References
3.4.10 Generators
[Link].complete_bipartite_graph
Notes
[Link].configuration_model
Notes
The sum of the two sequences must be equal: sum(aseq)=sum(bseq) If no graph type is specified use MultiGraph
with parallel edges. If you want a graph with no parallel edges use create_using=Graph() but then the resulting
degree sequences might not be exact.
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
This function is not imported in the main namespace. To use it use [Link].configuration_model
[Link].havel_hakimi_graph
Notes
The sum of the two sequences must be equal: sum(aseq)=sum(bseq) If no graph type is specified use MultiGraph
with parallel edges. If you want a graph with no parallel edges use create_using=Graph() but then the resulting
degree sequences might not be exact.
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
This function is not imported in the main namespace. To use it use [Link].havel_hakimi_graph
[Link].reverse_havel_hakimi_graph
Notes
The sum of the two sequences must be equal: sum(aseq)=sum(bseq) If no graph type is specified use MultiGraph
with parallel edges. If you want a graph with no parallel edges use create_using=Graph() but then the resulting
degree sequences might not be exact.
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
This function is not imported in the main namespace. To use it use [Link].reverse_havel_hakimi_graph
[Link].alternating_havel_hakimi_graph
Notes
The sum of the two sequences must be equal: sum(aseq)=sum(bseq) If no graph type is specified use MultiGraph
with parallel edges. If you want a graph with no parallel edges use create_using=Graph() but then the resulting
degree sequences might not be exact.
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
This function is not imported in the main namespace. To use it use [Link].alternating_havel_hakimi_graph
[Link].preferential_attachment_graph
References
Notes
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
This function is not imported in the main namespace. To use it use [Link].preferential_attachment_graph
[Link].random_graph
Notes
The bipartite random graph algorithm chooses each of the n*m (undirected) or 2*nm (directed) possible edges
with probability p.
This algorithm is 𝑂(𝑛 + 𝑚) where 𝑚 is the expected number of edges.
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
This function is not imported in the main namespace. To use it use [Link].random_graph
See also:
gnp_random_graph(), configuration_model()
References
[Link].gnmk_random_graph
Examples
Notes
3.4.11 Covering
[Link].min_edge_cover
min_edge_cover(G, matching_algorithm=None)
Returns a set of edges which constitutes the minimum edge cover of the graph.
The smallest edge cover can be found in polynomial time by finding a maximum matching and extending it
greedily so that all nodes are covered.
Parameters
• G (NetworkX graph) – An undirected bipartite graph.
• matching_algorithm (function) – A function that returns a maximum cardinality matching
in a given bipartite graph. The function must take one input, the graph G, and return a dic-
tionary mapping each node to its mate. If not specified, hopcroft_karp_matching()
will be used. Other possibilities include eppstein_matching(),
Returns A set of the edges in a minimum edge cover of the graph, given as pairs of nodes. It contains
both the edges (u, v) and (v, u) for given nodes u and v among the edges of minimum
edge cover.
Return type set
Notes
An edge cover of a graph is a set of edges such that every node of the graph is incident to at least one edge of
the set. A minimum edge cover is an edge covering of smallest cardinality.
Due to its implementation, the worst-case running time of this algorithm is bounded by the worst-case running
time of the function matching_algorithm.
3.5 Boundary
3.5.1 [Link].edge_boundary
Notes
3.5.2 [Link].node_boundary
Notes
3.6 Bridges
Bridge-finding algorithms.
3.6.1 [Link]
bridges(G, root=None)
Generate all bridges in a graph.
A bridge in a graph is an edge whose removal causes the number of connected components of the graph to
increase. Equivalently, a bridge is an edge that does not belong to any cycle.
Parameters
• G (undirected graph)
• root (node (optional)) – A node in the graph G. If specified, only the bridges in the connected
component containing this node will be returned.
Yields e (edge) – An edge in the graph whose removal disconnects the graph (or causes the number
of connected components to increase).
Raises NodeNotFound – If root is not in the graph G.
Examples
>>> G = nx.barbell_graph(10, 0)
>>> list([Link](G))
[(9, 10)]
Notes
This is an implementation of the algorithm described in _[1]. An edge is a bridge if and only if it is not contained
in any chain. Chains are found using the networkx.chain_decomposition() function.
Ignoring polylogarithmic factors, the worst-case time complexity is the same as the networkx.
chain_decomposition() function, 𝑂(𝑚 + 𝑛), where 𝑛 is the number of nodes in the graph and 𝑚 is
the number of edges.
References
3.6.2 [Link].has_bridges
has_bridges(G, root=None)
Decide whether a graph has any bridges.
A bridge in a graph is an edge whose removal causes the number of connected components of the graph to
increase.
Parameters
• G (undirected graph)
• root (node (optional)) – A node in the graph G. If specified, only the bridges in the connected
component containing this node will be considered.
Returns Whether the graph (or the connected component containing root) has any bridges.
Return type bool
Raises NodeNotFound – If root is not in the graph G.
Examples
>>> G = nx.barbell_graph(10, 0)
>>> nx.has_bridges(G)
True
>>> G = nx.cycle_graph(5)
>>> nx.has_bridges(G)
False
Notes
This implementation uses the [Link]() function, so it shares its worst-case time complexity,
𝑂(𝑚 + 𝑛), ignoring polylogarithmic factors, where 𝑛 is the number of nodes in the graph and 𝑚 is the number
of edges.
3.6.3 [Link].local_bridges
Examples
A cycle graph has every edge a local bridge with span N-1.
>>> G = nx.cycle_graph(9)
>>> (0, 8, 8) in set(nx.local_bridges(G))
True
3.7 Centrality
3.7.1 Degree
[Link].degree_centrality
degree_centrality(G)
Compute the degree centrality for nodes.
The degree centrality for a node v is the fraction of nodes it is connected to.
Parameters G (graph) – A networkx graph
Returns nodes – Dictionary of nodes with degree centrality as the value.
Return type dictionary
See also:
betweenness_centrality(), load_centrality(), eigenvector_centrality()
Notes
The degree centrality values are normalized by dividing by the maximum possible degree in a simple graph n-1
where n is the number of nodes in G.
For multigraphs or graphs with self loops the maximum degree might be higher than n-1 and values of degree
centrality greater than 1 are possible.
[Link].in_degree_centrality
in_degree_centrality(G)
Compute the in-degree centrality for nodes.
The in-degree centrality for a node v is the fraction of nodes its incoming edges are connected to.
Parameters G (graph) – A NetworkX graph
Returns nodes – Dictionary of nodes with in-degree centrality as values.
Return type dictionary
Raises NetworkXNotImplemented – If G is undirected.
See also:
degree_centrality(), out_degree_centrality()
Notes
The degree centrality values are normalized by dividing by the maximum possible degree in a simple graph n-1
where n is the number of nodes in G.
For multigraphs or graphs with self loops the maximum degree might be higher than n-1 and values of degree
centrality greater than 1 are possible.
[Link].out_degree_centrality
out_degree_centrality(G)
Compute the out-degree centrality for nodes.
The out-degree centrality for a node v is the fraction of nodes its outgoing edges are connected to.
Parameters G (graph) – A NetworkX graph
Returns nodes – Dictionary of nodes with out-degree centrality as values.
Return type dictionary
Raises NetworkXNotImplemented – If G is undirected.
See also:
degree_centrality(), in_degree_centrality()
Notes
The degree centrality values are normalized by dividing by the maximum possible degree in a simple graph n-1
where n is the number of nodes in G.
For multigraphs or graphs with self loops the maximum degree might be higher than n-1 and values of degree
centrality greater than 1 are possible.
3.7.2 Eigenvector
eigenvector_centrality(G[, max_iter, tol, Compute the eigenvector centrality for the graph G.
. . . ])
eigenvector_centrality_numpy(G[, weight, Compute the eigenvector centrality for the graph G.
. . . ])
katz_centrality(G[, alpha, beta, max_iter, . . . ]) Compute the Katz centrality for the nodes of the graph
G.
katz_centrality_numpy(G[, alpha, beta, . . . ]) Compute the Katz centrality for the graph G.
[Link].eigenvector_centrality
𝐴𝑥 = 𝜆𝑥
where 𝐴 is the adjacency matrix of the graph G with eigenvalue 𝜆. By virtue of the Perron–Frobenius theorem,
there is a unique solution 𝑥, all of whose entries are positive, if 𝜆 is the largest eigenvalue of the adjacency
matrix 𝐴 (2 ).
Parameters
• G (graph) – A networkx graph
• max_iter (integer, optional (default=100)) – Maximum number of iterations in power
method.
• tol (float, optional (default=1.0e-6)) – Error tolerance used to check convergence in power
method iteration.
• nstart (dictionary, optional (default=None)) – Starting value of eigenvector iteration for
each node.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
Returns nodes – Dictionary of nodes with eigenvector centrality as the value.
Return type dictionary
2 Mark E. J. Newman. Networks: An Introduction. Oxford University Press, USA, 2010, pp. 169.
Examples
>>> G = nx.path_graph(4)
>>> centrality = nx.eigenvector_centrality(G)
>>> sorted((v, f"{c:0.2f}") for v, c in [Link]())
[(0, '0.37'), (1, '0.60'), (2, '0.60'), (3, '0.37')]
Raises
• NetworkXPointlessConcept – If the graph G is the null graph.
• NetworkXError – If each value in nstart is zero.
• PowerIterationFailedConvergence – If the algorithm fails to converge to the
specified tolerance within the specified number of iterations of the power iteration method.
See also:
eigenvector_centrality_numpy(), pagerank(), hits()
Notes
References
[Link].eigenvector_centrality_numpy
𝐴𝑥 = 𝜆𝑥
where 𝐴 is the adjacency matrix of the graph G with eigenvalue 𝜆. By virtue of the Perron–Frobenius theorem,
there is a unique and positive solution if 𝜆 is the largest eigenvalue associated with the eigenvector of the
adjacency matrix 𝐴 (2 ).
Parameters
• G (graph) – A networkx graph
1 Phillip Bonacich. “Power and Centrality: A Family of Measures.” American Journal of Sociology 92(5):1170–1182, 1986 <[Link]
[Link]/hse/2014/socialnetworks/papers/[Link]>
2 Mark E. J. Newman: Networks: An Introduction. Oxford University Press, USA, 2010, pp. 169.
• weight (None or string, optional (default=None)) – The name of the edge attribute used as
weight. If None, all edge weights are considered equal.
• max_iter (integer, optional (default=100)) – Maximum number of iterations in power
method.
• tol (float, optional (default=1.0e-6)) – Relative accuracy for eigenvalues (stopping crite-
rion). The default value of 0 implies machine precision.
Returns nodes – Dictionary of nodes with eigenvector centrality as the value.
Return type dictionary
Examples
>>> G = nx.path_graph(4)
>>> centrality = nx.eigenvector_centrality_numpy(G)
>>> print([f"{node} {centrality[node]:0.2f}" for node in centrality])
['0 0.37', '1 0.60', '2 0.60', '3 0.37']
See also:
eigenvector_centrality(), pagerank(), hits()
Notes
References
[Link].katz_centrality
Katz centrality computes the relative influence of a node within a network by measuring the number of the
immediate neighbors (first degree nodes) and also all other nodes in the network that connect to the node under
consideration through these immediate neighbors.
Extra weight can be provided to immediate neighbors through the parameter 𝛽. Connections made with distant
neighbors are, however, penalized by an attenuation factor 𝛼 which should be strictly less than the inverse largest
eigenvalue of the adjacency matrix in order for the Katz centrality to be computed correctly. More information
is provided in1 .
Parameters
• G (graph) – A NetworkX graph.
• alpha (float) – Attenuation factor
• beta (scalar or dictionary, optional (default=1.0)) – Weight attributed to the immediate
neighborhood. If not a scalar, the dictionary must have an value for every node.
• max_iter (integer, optional (default=1000)) – Maximum number of iterations in power
method.
• tol (float, optional (default=1.0e-6)) – Error tolerance used to check convergence in power
method iteration.
• nstart (dictionary, optional) – Starting value of Katz iteration for each node.
• normalized (bool, optional (default=True)) – If True normalize the resulting values.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
Returns nodes – Dictionary of nodes with Katz centrality as the value.
Return type dictionary
Raises
• NetworkXError – If the parameter beta is not a scalar but lacks a value for at least one
node
• PowerIterationFailedConvergence – If the algorithm fails to converge to the
specified tolerance within the specified number of iterations of the power iteration method.
Examples
See also:
katz_centrality_numpy(), eigenvector_centrality(), eigenvector_centrality_numpy(),
pagerank(), hits()
1 Mark E. J. Newman: Networks: An Introduction. Oxford University Press, USA, 2010, p. 720.
Notes
References
[Link].katz_centrality_numpy
Examples
See also:
katz_centrality(), eigenvector_centrality_numpy(), eigenvector_centrality(),
pagerank(), hits()
Notes
References
3.7.3 Closeness
[Link].closeness_centrality
where d(v, u) is the shortest-path distance between v and u, and n is the number of nodes that can reach
u. Notice that the closeness distance function computes the incoming distance to u for directed graphs. To use
outward distance, act on [Link]().
Notice that higher values of closeness indicate higher centrality.
Wasserman and Faust propose an improved formula for graphs with more than one connected component. The
result is “a ratio of the fraction of actors in the group who are reachable, to the average distance” from the
reachable actors2 . You might think this scale factor is inverted but it is not. As is, nodes from small components
receive a smaller closeness value. Letting N denote the number of nodes in the graph,
𝑛−1 𝑛−1
𝐶𝑊 𝐹 (𝑢) = ,
𝑁 − 1 𝑛−1
∑︀
𝑣=1 𝑑(𝑣, 𝑢)
Parameters
• G (graph) – A NetworkX graph
• u (node, optional) – Return only the value for node u
• distance (edge attribute key, optional (default=None)) – Use the specified edge attribute as
the edge distance in shortest path calculations
• wf_improved (bool, optional (default=True)) – If True, scale by the fraction of nodes reach-
able. This gives the Wasserman and Faust improved formula. For single component graphs
it is the same as the original formula.
Returns nodes – Dictionary of nodes with closeness centrality as the value.
Return type dictionary
See also:
betweenness_centrality(), load_centrality(), eigenvector_centrality(),
degree_centrality(), incremental_closeness_centrality()
Notes
The closeness centrality is normalized to (n-1)/(|G|-1) where n is the number of nodes in the connected
part of graph containing the node. If the graph is not completely connected, this algorithm computes the close-
ness centrality for each connected part separately scaled by that parts size.
If the ‘distance’ keyword is set to an edge attribute key then the shortest-path length will be computed using
Dijkstra’s algorithm with that edge attribute as the edge weight.
The closeness centrality uses inward distance to a node, not outward. If you want to use outword distances apply
the function to [Link]()
1 Linton C. Freeman: Centrality in networks: I. Conceptual clarification. Social Networks 1:215-239, 1979. [Link]
socialnetworks/papers/[Link]
2 pg. 201 of Wasserman, S. and Faust, K., Social Network Analysis: Methods and Applications, 1994, Cambridge University Press.
In NetworkX 2.2 and earlier a bug caused Dijkstra’s algorithm to use the outward distance rather than the inward
distance. If you use a ‘distance’ keyword and a DiGraph, your results will change between v2.2 and v2.3.
References
[Link].incremental_closeness_centrality
where d(v, u) is the shortest-path distance between v and u, and n is the number of nodes in the graph.
Notice that higher values of closeness indicate higher centrality.
Parameters
• G (graph) – A NetworkX graph
• edge (tuple) – The modified edge (u, v) in the graph.
• prev_cc (dictionary) – The previous closeness centrality for all nodes in the graph.
• insertion (bool, optional) – If True (default) the edge was inserted, otherwise it was deleted
from the graph.
• wf_improved (bool, optional (default=True)) – If True, scale by the fraction of nodes reach-
able. This gives the Wasserman and Faust improved formula. For single component graphs
it is the same as the original formula.
Returns nodes – Dictionary of nodes with closeness centrality as the value.
Return type dictionary
1 Freeman, L.C., 1979. Centrality in networks: I. Conceptual clarification. Social Networks 1, 215–239. [Link]
friedkin/Syllabi/Soc146/[Link]
See also:
betweenness_centrality(), load_centrality(), eigenvector_centrality(),
degree_centrality(), closeness_centrality()
Notes
The closeness centrality is normalized to (n-1)/(|G|-1) where n is the number of nodes in the connected
part of graph containing the node. If the graph is not completely connected, this algorithm computes the close-
ness centrality for each connected part separately.
References
[Link].current_flow_closeness_centrality
Notes
References
[Link].information_centrality
Notes
1016/0378-8733(89)90016-6
1 Ulrik Brandes and Daniel Fleischer, Centrality Measures Based on Current Flow. Proc. 22nd Symp. Theoretical Aspects of Computer Science
1016/0378-8733(89)90016-6
References
[Link].betweenness_centrality
where 𝑉 is the set of nodes, 𝜎(𝑠, 𝑡) is the number of shortest (𝑠, 𝑡)-paths, and 𝜎(𝑠, 𝑡|𝑣) is the number of those
paths passing through some node 𝑣 other than 𝑠, 𝑡. If 𝑠 = 𝑡, 𝜎(𝑠, 𝑡) = 1, and if 𝑣 ∈ 𝑠, 𝑡, 𝜎(𝑠, 𝑡|𝑣) = 02 .
Parameters
• G (graph) – A NetworkX graph.
• k (int, optional (default=None)) – If k is not None use k node samples to estimate between-
ness. The value of k <= n where n is the number of nodes in the graph. Higher values give
better approximation.
• normalized (bool, optional) – If True the betweenness values are normalized by 2/
((n-1)(n-2)) for graphs, and 1/((n-1)(n-2)) for directed graphs where n is the
number of nodes in G.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
• endpoints (bool, optional) – If True include the endpoints in the shortest path counts.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness. Note that this is only used if k is not None.
Returns nodes – Dictionary of nodes with betweenness centrality as the value.
Return type dictionary
See also:
edge_betweenness_centrality(), load_centrality()
2 Ulrik Brandes: On Variants of Shortest-Path Betweenness Centrality and their Generic Computation. Social Networks 30(2):136-145, 2008.
[Link]
Notes
The algorithm is from Ulrik Brandes1 . See4 for the original first published version and2 for details on algorithms
for variations and related metrics.
For approximate betweenness calculations set k=#samples to use k nodes (“pivots”) to estimate the betweenness
values. For an estimate of the number of pivots needed see3 .
For weighted graphs the edge weights must be greater than zero. Zero edge weights can produce an infinite
number of equal length paths between pairs of nodes.
The total number of paths between source and target is counted differently for directed and undirected graphs.
Directed paths are easy to count. Undirected paths are tricky: should a path from “u” to “v” count as 1 undirected
path or as 2 directed paths?
For betweenness_centrality we report the number of undirected paths when G is undirected.
For betweenness_centrality_subset the reporting is different. If the source and target subsets are the same, then
we want to count undirected paths. But if the source and target subsets differ – for example, if sources is {0}
and targets is {1}, then we are only counting the paths in one direction. They are undirected paths but we are
counting them in a directed way. To count them as undirected paths, each should count as half a path.
References
[Link].betweenness_centrality_source
[Link].betweenness_centrality_subset
where 𝑆 is the set of sources, 𝑇 is the set of targets, 𝜎(𝑠, 𝑡) is the number of shortest (𝑠, 𝑡)-paths, and 𝜎(𝑠, 𝑡|𝑣)
is the number of those paths passing through some node 𝑣 other than 𝑠, 𝑡. If 𝑠 = 𝑡, 𝜎(𝑠, 𝑡) = 1, and if 𝑣 ∈ 𝑠, 𝑡,
𝜎(𝑠, 𝑡|𝑣) = 02 .
Parameters
• G (graph) – A NetworkX graph.
• sources (list of nodes) – Nodes to use as sources for shortest paths in betweenness
• targets (list of nodes) – Nodes to use as targets for shortest paths in betweenness
• normalized (bool, optional) – If True the betweenness values are normalized by 2/((𝑛 −
1)(𝑛 − 2)) for graphs, and 1/((𝑛 − 1)(𝑛 − 2)) for directed graphs where 𝑛 is the number of
nodes in G.
1 Ulrik Brandes: A Faster Algorithm for Betweenness Centrality. Journal of Mathematical Sociology 25(2):163-177, 2001. [Link]
[Link]/algo/publications/[Link]
4 Linton C. Freeman: A set of measures of centrality based on betweenness. Sociometry 40: 35–41, 1977 [Link]
3 Ulrik Brandes and Christian Pich: Centrality Estimation in Large Networks. International Journal of Bifurcation and Chaos 17(7):2303-2318,
2007. [Link]
2 Ulrik Brandes: On Variants of Shortest-Path Betweenness Centrality and their Generic Computation. Social Networks 30(2):136-145, 2008.
[Link]
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
Returns nodes – Dictionary of nodes with betweenness centrality as the value.
Return type dictionary
See also:
edge_betweenness_centrality(), load_centrality()
Notes
References
[Link].edge_betweenness_centrality
where 𝑉 is the set of nodes, 𝜎(𝑠, 𝑡) is the number of shortest (𝑠, 𝑡)-paths, and 𝜎(𝑠, 𝑡|𝑒) is the number of those
paths passing through edge 𝑒2 .
Parameters
• G (graph) – A NetworkX graph.
• k (int, optional (default=None)) – If k is not None use k node samples to estimate between-
ness. The value of k <= n where n is the number of nodes in the graph. Higher values give
better approximation.
1 Ulrik Brandes, A Faster Algorithm for Betweenness Centrality. Journal of Mathematical Sociology 25(2):163-177, 2001. [Link]
[Link]/algo/publications/[Link]
2 Ulrik Brandes: On Variants of Shortest-Path Betweenness Centrality and their Generic Computation. Social Networks 30(2):136-145, 2008.
[Link]
• normalized (bool, optional) – If True the betweenness values are normalized by 2/(𝑛(𝑛 −
1)) for graphs, and 1/(𝑛(𝑛 − 1)) for directed graphs where 𝑛 is the number of nodes in G.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness. Note that this is only used if k is not None.
Returns edges – Dictionary of edges with betweenness centrality as the value.
Return type dictionary
See also:
betweenness_centrality(), edge_load()
Notes
References
[Link].edge_betweenness_centrality_subset
where 𝑆 is the set of sources, 𝑇 is the set of targets, 𝜎(𝑠, 𝑡) is the number of shortest (𝑠, 𝑡)-paths, and 𝜎(𝑠, 𝑡|𝑒)
is the number of those paths passing through edge 𝑒2 .
Parameters
• G (graph) – A networkx graph.
• sources (list of nodes) – Nodes to use as sources for shortest paths in betweenness
• targets (list of nodes) – Nodes to use as targets for shortest paths in betweenness
• normalized (bool, optional) – If True the betweenness values are normalized by 2/
(n(n-1)) for graphs, and 1/(n(n-1)) for directed graphs where n is the number of
nodes in G.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
Returns edges – Dictionary of edges with Betweenness centrality as the value.
Return type dictionary
1 A Faster Algorithm for Betweenness Centrality. Ulrik Brandes, Journal of Mathematical Sociology 25(2):163-177, 2001. [Link]
[Link]/algo/publications/[Link]
2 Ulrik Brandes: On Variants of Shortest-Path Betweenness Centrality and their Generic Computation. Social Networks 30(2):136-145, 2008.
[Link]
See also:
betweenness_centrality(), edge_load()
Notes
References
[Link].current_flow_betweenness_centrality
[Link]/algo/publications/[Link]
2 A measure of betweenness centrality based on random walks, M. E. J. Newman, Social Networks 27, 39-54 (2005).
• solver (string (default=’full’)) – Type of linear solver to use for computing the flow matrix.
Options are “full” (uses most memory), “lu” (recommended), and “cg” (uses least memory).
Returns nodes – Dictionary of nodes with betweenness centrality as the value.
Return type dictionary
See also:
approximate_current_flow_betweenness_centrality(), betweenness_centrality(),
edge_betweenness_centrality(), edge_current_flow_betweenness_centrality()
Notes
Current-flow betweenness can be computed in 𝑂(𝐼(𝑛 − 1) + 𝑚𝑛 log 𝑛) time1 , where 𝐼(𝑛 − 1) is the time
3
√ the inverse Laplacian. For a full matrix this is 𝑂(𝑛 ) but using sparse methods you can
needed to compute
achieve 𝑂(𝑛𝑚 𝑘) where 𝑘 is the Laplacian matrix condition number.
The space required is 𝑂(𝑛𝑤) where 𝑤 is the width of the sparse Laplacian matrix. Worse case is 𝑤 = 𝑛 for
𝑂(𝑛2 ).
If the edges have a ‘weight’ attribute they will be used as weights in this algorithm. Unspecified weights are set
to 1.
References
[Link].edge_current_flow_betweenness_centrality
Raises NetworkXError – The algorithm does not support DiGraphs. If the input graph is an
instance of DiGraph class, NetworkXError is raised.
See also:
betweenness_centrality(), edge_betweenness_centrality(),
current_flow_betweenness_centrality()
Notes
Current-flow betweenness can be computed in 𝑂(𝐼(𝑛 − 1) + 𝑚𝑛 log 𝑛) time1 , where 𝐼(𝑛 − 1) is the time
3
√ the inverse Laplacian. For a full matrix this is 𝑂(𝑛 ) but using sparse methods you can
needed to compute
achieve 𝑂(𝑛𝑚 𝑘) where 𝑘 is the Laplacian matrix condition number.
The space required is 𝑂(𝑛𝑤) where 𝑤 is the width of the sparse Laplacian matrix. Worse case is 𝑤 = 𝑛 for
𝑂(𝑛2 ).
If the edges have a ‘weight’ attribute they will be used as weights in this algorithm. Unspecified weights are set
to 1.
References
[Link].approximate_current_flow_betweenness_centrality
See also:
current_flow_betweenness_centrality()
Notes
√
The running time is 𝑂((1/𝜖2 )𝑚 𝑘 log 𝑛) and the space required is 𝑂(𝑚) for 𝑛 nodes and 𝑚 edges.
If the edges have a ‘weight’ attribute they will be used as weights in this algorithm. Unspecified weights are set
to 1.
References
[Link].current_flow_betweenness_centrality_subset
Notes
Current-flow betweenness can be computed in 𝑂(𝐼(𝑛 − 1) + 𝑚𝑛 log 𝑛) time1 , where 𝐼(𝑛 − 1) is the time
3
√ the inverse Laplacian. For a full matrix this is 𝑂(𝑛 ) but using sparse methods you can
needed to compute
achieve 𝑂(𝑛𝑚 𝑘) where 𝑘 is the Laplacian matrix condition number.
The space required is 𝑂(𝑛𝑤) where 𝑤 is the width of the sparse Laplacian matrix. Worse case is 𝑤 = 𝑛 for
𝑂(𝑛2 ).
If the edges have a ‘weight’ attribute they will be used as weights in this algorithm. Unspecified weights are set
to 1.
References
[Link].edge_current_flow_betweenness_centrality_subset
Notes
Current-flow betweenness can be computed in 𝑂(𝐼(𝑛 − 1) + 𝑚𝑛 log 𝑛) time1 , where 𝐼(𝑛 − 1) is the time
3
√ the inverse Laplacian. For a full matrix this is 𝑂(𝑛 ) but using sparse methods you can
needed to compute
achieve 𝑂(𝑛𝑚 𝑘) where 𝑘 is the Laplacian matrix condition number.
The space required is 𝑂(𝑛𝑤) where 𝑤 is the width of the sparse Laplacian matrix. Worse case is 𝑤 = 𝑛 for
𝑂(𝑛2 ).
If the edges have a ‘weight’ attribute they will be used as weights in this algorithm. Unspecified weights are set
to 1.
References
[Link].communicability_betweenness_centrality
communicability_betweenness_centrality(G, normalized=True)
Returns subgraph communicability for all pairs of nodes in G.
Communicability betweenness measure makes use of the number of walks connecting every pair of nodes as the
basis of a betweenness centrality measure.
Parameters G (graph)
Returns nodes – Dictionary of nodes with communicability betweenness as the value.
Return type dictionary
Raises NetworkXError – If the graph is not undirected and simple.
Notes
Let G=(V,E) be a simple undirected graph with n nodes and m edges, and A denote the adjacency matrix of G.
Let G(r)=(V,E(r)) be the graph resulting from removing all edges connected to node r but not the node
itself.
The adjacency matrix for G(r) is A+E(r), where E(r) has nonzeros only in row and column r.
The subraph betweenness of a node r is1
1 ∑︁ ∑︁ 𝐺𝑝𝑟𝑞
𝜔𝑟 = , 𝑝 ̸= 𝑞, 𝑞 ̸= 𝑟,
𝐶 𝑝 𝑞 𝐺𝑝𝑞
774. [Link]
The resulting omega_{r} takes values between zero and one. The lower bound cannot be attained for a
connected graph, and the upper bound is attained in the star graph.
References
Examples
>>> G = [Link]([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
>>> cbc = nx.communicability_betweenness_centrality(G)
>>> print([f"{node} {cbc[node]:0.2f}" for node in sorted(cbc)])
['0 0.03', '1 0.45', '2 0.51', '3 0.45', '4 0.40', '5 0.19', '6 0.03']
[Link].group_betweenness_centrality
where 𝑉 is the set of nodes, 𝜎(𝑠, 𝑡) is the number of shortest (𝑠, 𝑡)-paths, and 𝜎(𝑠, 𝑡|𝐶) is the number of those
paths passing through some node in group 𝐶. Note that (𝑠, 𝑡) are not members of the group (𝑉 − 𝐶 is the set of
nodes in 𝑉 that are not in 𝐶).
Parameters
• G (graph) – A NetworkX graph.
• C (list or set) – C is a group of nodes which belong to G, for which group betweenness
centrality is to be calculated.
• normalized (bool, optional) – If True, group betweenness is normalized by 2/
((|V|-|C|)(|V|-|C|-1)) for graphs and 1/((|V|-|C|)(|V|-|C|-1)) for di-
rected graphs where |V| is the number of nodes in G and |C| is the number of nodes in
C.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
Notes
The measure is described in1 . The algorithm is an extension of the one proposed by Ulrik Brandes for between-
ness centrality of nodes. Group betweenness is also mentioned in his paper2 along with the algorithm. The
importance of the measure is discussed in3 .
The number of nodes in the group must be a maximum of n - 2 where n is the total number of nodes in the
graph.
For weighted graphs the edge weights must be greater than zero. Zero edge weights can produce an infinite
number of equal length paths between pairs of nodes.
References
[Link].group_closeness_centrality
group_closeness_centrality(G, S, weight=None)
Compute the group closeness centrality for a group of nodes.
Group closeness centrality of a group of nodes 𝑆 is a measure of how close the group is to the other nodes in
the graph.
|𝑉 − 𝑆|
𝑐𝑐𝑙𝑜𝑠𝑒 (𝑆) = ∑︀
𝑣∈𝑉 −𝑆 𝑑𝑆,𝑣
𝑑𝑆,𝑣 = 𝑚𝑖𝑛𝑢∈𝑆 (𝑑𝑢,𝑣 )
where 𝑉 is the set of nodes, 𝑑𝑆,𝑣 is the distance of the group 𝑆 from 𝑣 defined as above. (𝑉 − 𝑆 is the set of
nodes in 𝑉 that are not in 𝑆).
Parameters
• G (graph) – A NetworkX graph.
• S (list or set) – S is a group of nodes which belong to G, for which group closeness centrality
is to be calculated.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
Raises NodeNotFound – If node(s) in S are not present in G.
Returns closeness – Group closeness centrality of the group S.
Return type float
1 M G Everett and S P Borgatti: The Centrality of Groups and Classes. Journal of Mathematical Sociology. 23(3): 181-201. 1999. http:
//[Link]/borgatti/group_centrality.htm
2 Ulrik Brandes: On Variants of Shortest-Path Betweenness Centrality and their Generic Computation. Social Networks 30(2):136-145, 2008.
[Link]
3 Sourav Medya et. al.: Group Centrality Maximization via Network Design. SIAM International Conference on Data Mining, SDM 2018,
126–134. [Link]
See also:
closeness_centrality()
Notes
The measure was introduced in1 . The formula implemented here is described in2 .
Higher values of closeness indicate greater centrality.
It is assumed that 1 / 0 is 0 (required in the case of directed graphs, or when a shortest path length is 0).
The number of nodes in the group must be a maximum of n - 1 where n is the total number of nodes in the
graph.
For directed graphs, the incoming distance is utilized here. To use the outward distance, act on [Link]().
For weighted graphs the edge weights must be greater than zero. Zero edge weights can produce an infinite
number of equal length paths between pairs of nodes.
References
[Link].group_degree_centrality
group_degree_centrality(G, S)
Compute the group degree centrality for a group of nodes.
Group degree centrality of a group of nodes 𝑆 is the fraction of non-group members connected to group mem-
bers.
Parameters
• G (graph) – A NetworkX graph.
• S (list or set) – S is a group of nodes which belong to G, for which group degree centrality
is to be calculated.
Raises NetworkXError – If node(s) in S are not in G.
Returns centrality – Group degree centrality of the group S.
Return type float
See also:
degree_centrality(), group_in_degree_centrality(), group_out_degree_centrality()
1 M G Everett and S P Borgatti: The Centrality of Groups and Classes. Journal of Mathematical Sociology. 23(3): 181-201. 1999. http:
//[Link]/borgatti/group_centrality.htm
2 J. Zhao et. al.: Measuring and Maximizing Group Closeness Centrality over Disk Resident Graphs. WWWConference Proceedings, 2014.
689-694. [Link]
Notes
References
[Link].group_in_degree_centrality
group_in_degree_centrality(G, S)
Compute the group in-degree centrality for a group of nodes.
Group in-degree centrality of a group of nodes 𝑆 is the fraction of non-group members connected to group
members by incoming edges.
Parameters
• G (graph) – A NetworkX graph.
• S (list or set) – S is a group of nodes which belong to G, for which group in-degree centrality
is to be calculated.
Returns centrality – Group in-degree centrality of the group S.
Return type float
Raises
• NetworkXNotImplemented – If G is undirected.
• NodeNotFound – If node(s) in S are not in G.
See also:
degree_centrality(), group_degree_centrality(), group_out_degree_centrality()
Notes
The number of nodes in the group must be a maximum of n - 1 where n is the total number of nodes in the
graph.
[Link](i) gives nodes with an outward edge from i, in a DiGraph, so for group in-degree centrality,
the reverse graph is used.
[Link].group_out_degree_centrality
group_out_degree_centrality(G, S)
Compute the group out-degree centrality for a group of nodes.
Group out-degree centrality of a group of nodes 𝑆 is the fraction of non-group members connected to group
members by outgoing edges.
Parameters
• G (graph) – A NetworkX graph.
1 M G Everett and S P Borgatti: The Centrality of Groups and Classes. Journal of Mathematical Sociology. 23(3): 181-201. 1999. http:
//[Link]/borgatti/group_centrality.htm
• S (list or set) – S is a group of nodes which belong to G, for which group in-degree centrality
is to be calculated.
Returns centrality – Group out-degree centrality of the group S.
Return type float
Raises
• NetworkXNotImplemented – If G is undirected.
• NodeNotFound – If node(s) in S are not in G.
See also:
degree_centrality(), group_degree_centrality(), group_in_degree_centrality()
Notes
The number of nodes in the group must be a maximum of n - 1 where n is the total number of nodes in the
graph.
[Link](i) gives nodes with an outward edge from i, in a DiGraph, so for group out-degree centrality,
the graph itself is used.
3.7.9 Load
[Link].load_centrality
Notes
Load centrality is slightly different than betweenness. It was originally introduced by2 . For this load algorithm
see1 .
References
[Link].edge_load_centrality
edge_load_centrality(G, cutoff=False)
Compute edge load.
WARNING: This concept of edge load has not been analysed or discussed outside of NetworkX that we know
of. It is based loosely on load_centrality in the sense that it counts the number of shortest paths which cross
each edge. This function is for demonstration and testing purposes.
Parameters
• G (graph) – A networkx graph
• cutoff (bool, optional (default=False)) – If specified, only consider paths of length <= cut-
off.
Returns
• A dict keyed by edge 2-tuple to the number of shortest paths
• which use that edge. Where more than one path is shortest
• the count is divided equally among paths.
3.7.10 Subgraph
[Link].subgraph_centrality
subgraph_centrality(G)
Returns subgraph centrality for each node in G.
Subgraph centrality of a node n is the sum of weighted closed walks of all lengths starting and ending at node
n. The weights decrease with path length. Each closed walk is associated with a connected subgraph (1 ).
Parameters G (graph)
Returns nodes – Dictionary of nodes with subgraph centrality as the value.
Return type dictionary
2 Kwang-Il Goh, Byungnam Kahng and Doochul Kim Universal behavior of Load Distribution in Scale-Free Networks. Physical Review Letters
2001. [Link]
1 Ernesto Estrada, Juan A. Rodriguez-Velazquez, “Subgraph centrality in complex networks”, Physical Review E 71, 056103 (2005). https:
//[Link]/abs/cond-mat/0504730
Notes
This version of the algorithm computes eigenvalues and eigenvectors of the adjacency matrix.
Subgraph centrality of a node u in G can be found using a spectral decomposition of the adjacency matrix1 ,
𝑁
∑︁
𝑆𝐶(𝑢) = (𝑣𝑗𝑢 )2 𝑒𝜆𝑗 ,
𝑗=1
where v_j is an eigenvector of the adjacency matrix A of G corresponding corresponding to the eigenvalue
lambda_j.
Examples
(Example from1 ) >>> G = [Link]( . . . [ . . . (1, 2), . . . (1, 5), . . . (1, 8), . . . (2, 3), . . . (2, 8), . . . (3, 4), . . .
(3, 6), . . . (4, 5), . . . (4, 7), . . . (5, 6), . . . (6, 7), . . . (7, 8), . . . ] . . . ) >>> sc = nx.subgraph_centrality(G)
>>> print([f”{node} {sc[node]:0.2f}” for node in sorted(sc)]) [‘1 3.90’, ‘2 3.90’, ‘3 3.64’, ‘4 3.71’, ‘5 3.64’, ‘6
3.71’, ‘7 3.64’, ‘8 3.90’]
References
[Link].subgraph_centrality_exp
subgraph_centrality_exp(G)
Returns the subgraph centrality for each node of G.
Subgraph centrality of a node n is the sum of weighted closed walks of all lengths starting and ending at node
n. The weights decrease with path length. Each closed walk is associated with a connected subgraph (1 ).
Parameters G (graph)
Returns nodes – Dictionary of nodes with subgraph centrality as the value.
Return type dictionary
Raises NetworkXError – If the graph is not undirected and simple.
See also:
Notes
References
Examples
(Example from1 ) >>> G = [Link]( . . . [ . . . (1, 2), . . . (1, 5), . . . (1, 8), . . . (2, 3), . . . (2, 8), . . . (3, 4), . . .
(3, 6), . . . (4, 5), . . . (4, 7), . . . (5, 6), . . . (6, 7), . . . (7, 8), . . . ] . . . ) >>> sc = nx.subgraph_centrality_exp(G)
>>> print([f”{node} {sc[node]:0.2f}” for node in sorted(sc)]) [‘1 3.90’, ‘2 3.90’, ‘3 3.64’, ‘4 3.71’, ‘5 3.64’, ‘6
3.71’, ‘7 3.64’, ‘8 3.90’]
[Link].estrada_index
estrada_index(G)
Returns the Estrada index of a the graph G.
The Estrada Index is a topological index of folding or 3D “compactness” (1 ).
Parameters G (graph)
Returns estrada index
Return type float
Raises NetworkXError – If the graph is not undirected and simple.
Notes
[Link]
References
Examples
>>> G = [Link]([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
>>> ei = nx.estrada_index(G)
>>> print(f"{ei:0.5}")
20.55
[Link].harmonic_centrality
Notes
If the ‘distance’ keyword is set to an edge attribute key then the shortest-path length will be computed using
Dijkstra’s algorithm with that edge attribute as the edge weight.
References
3.7.12 Dispersion
[Link]
Notes
This implementation follows Lars Backstrom and Jon Kleinberg1 . Typical usage would be to run dispersion on
the ego network 𝐺𝑢 if 𝑢 were specified. Running dispersion() with neither 𝑢 nor 𝑣 specified can take some
time to complete.
References
3.7.13 Reaching
local_reaching_centrality(G, v[, paths, Returns the local reaching centrality of a node in a di-
. . . ]) rected graph.
global_reaching_centrality(G[, weight, Returns the global reaching centrality of a directed
. . . ]) graph.
1 Romantic Partnerships and the Dispersion of Social Ties: A Network Analysis of Relationship Status on Facebook. Lars Backstrom, Jon
Kleinberg. [Link]
[Link].local_reaching_centrality
Examples
>>> G = [Link]()
>>> G.add_edges_from([(1, 2), (1, 3)])
>>> nx.local_reaching_centrality(G, 3)
0.0
>>> G.add_edge(3, 2)
>>> nx.local_reaching_centrality(G, 3)
0.5
See also:
global_reaching_centrality()
References
[Link].global_reaching_centrality
10.1371/[Link].0033799
1 Mones, Enys, Lilla Vicsek, and Tamás Vicsek. “Hierarchy Measure for Complex Networks.” PLoS ONE 7.3 (2012): e33799. [Link]
10.1371/[Link].0033799
Informally, the local reaching centrality is the proportion of the graph that is reachable from the neighbors of
the node.
Parameters
• G (DiGraph) – A networkx DiGraph.
• weight (None or string, optional (default=None)) – Attribute to use for edge weights. If
None, each edge weight is assumed to be one. A higher weight implies a stronger connec-
tion between nodes and a shorter path length.
• normalized (bool, optional (default=True)) – Whether to normalize the edge weights by
the total sum of edge weights.
Returns h – The global reaching centrality of the graph.
Return type float
Examples
>>> G = [Link]()
>>> G.add_edge(1, 2)
>>> G.add_edge(1, 3)
>>> nx.global_reaching_centrality(G)
1.0
>>> G.add_edge(3, 2)
>>> nx.global_reaching_centrality(G)
0.75
See also:
local_reaching_centrality()
References
3.7.14 Percolation
[Link].percolation_centrality
Parameters
• G (graph) – A NetworkX graph.
• attribute (None or string, optional (default=’percolation’)) – Name of the node attribute to
use for percolation state, used if states is None.
• states (None or dict, optional (default=None)) – Specify percolation states for the nodes,
nodes as keys states as values.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
Returns nodes – Dictionary of nodes with percolation centrality as the value.
Return type dictionary
See also:
betweenness_centrality()
Notes
The algorithm is from Mahendra Piraveenan, Mikhail Prokopenko, and Liaquat Hossain1 Pair dependecies are
calculated and accumulated using2
For weighted graphs the edge weights must be greater than zero. Zero edge weights can produce an infinite
number of equal length paths between pairs of nodes.
References
[Link].second_order_centrality
second_order_centrality(G)
Compute the second order centrality for nodes of G.
The second order centrality of a given node is the standard deviation of the return times to that node of a
perpetual random walk on G:
Parameters G (graph) – A NetworkX connected and undirected graph.
Returns nodes – Dictionary keyed by node with second order centrality as the value.
Return type dictionary
1 Mahendra Piraveenan, Mikhail Prokopenko, Liaquat Hossain Percolation Centrality: Quantifying Graph-Theoretic Impact of Nodes during
[Link]/algo/publications/[Link]
Examples
>>> G = nx.star_graph(10)
>>> soc = nx.second_order_centrality(G)
>>> print(sorted([Link](), key=lambda x: x[1])[0][0]) # pick first id
0
Raises NetworkXException – If the graph G is empty, non connected or has negative weights.
See also:
betweenness_centrality()
Notes
References
3.7.16 Trophic
[Link].trophic_levels
trophic_levels(G, weight='weight')
Compute the trophic levels of nodes.
The trophic level of a node 𝑖 is
1 ∑︁
𝑠𝑖 = 1 + 𝑎𝑖𝑗 𝑠𝑗
𝑘𝑖𝑖𝑛 𝑗
1 Anne-Marie Kermarrec, Erwan Le Merrer, Bruno Sericola, Gilles Trédan “Second order centrality: Distributed assessment of nodes criticity
in complex networks”, Elsevier Computer Communications 34(5):619-628, 2011.
References
[Link].trophic_differences
trophic_differences(G, weight='weight')
Compute the trophic differences of the edges of a directed graph.
The trophic difference 𝑥𝑖 𝑗 for each edge is defined in Johnson et al.1 as:
𝑥𝑖 𝑗 = 𝑠𝑗 − 𝑠𝑖
References
[Link].trophic_incoherence_parameter
References
3.7.17 VoteRank
[Link]
voterank(G, number_of_nodes=None)
Select a list of influential nodes in a graph using VoteRank algorithm
VoteRank1 computes a ranking of the nodes in a graph G based on a voting scheme. With VoteRank, all nodes
vote for each of its in-neighbours and the node with the highest votes is elected iteratively. The voting ability of
out-neighbors of elected nodes is decreased in subsequent turns.
Note: We treat each edge independently in case of multigraphs.
Parameters
• G (graph) – A NetworkX graph.
• number_of_nodes (integer, optional) – Number of ranked nodes to extract (default all
nodes).
Returns voterank – Ordered list of computed seeds. Only nodes with positive number of votes are
returned.
Return type list
References
3.8 Chains
3.8.1 [Link].chain_decomposition
chain_decomposition(G, root=None)
Returns the chain decomposition of a graph.
The chain decomposition of a graph with respect a depth-first search tree is a set of cycles or paths derived from
the set of fundamental cycles of the tree in the following manner. Consider each fundamental cycle with respect
to the given tree, represented as a list of edges beginning with the nontree edge oriented away from the root of
the tree. For each fundamental cycle, if it overlaps with any previous fundamental cycle, just take the initial
non-overlapping segment, which is a path instead of a cycle. Each cycle or path is called a chain. For more
information, see1 .
1 Zhang, J.-X. et al. (2016). Identifying a set of influential spreaders in complex networks. Sci. Rep. 6, 27823; doi: 10.1038/srep27823.
1 Jens M. Schmidt (2013). “A simple test on 2-vertex- and 2-edge-connectivity.” Information Processing Letters, 113, 241–244. Elsevier.
<[Link]
Parameters
• G (undirected graph)
• root (node (optional)) – A node in the graph G. If specified, only the chain decomposition
for the connected component containing this node will be returned. This node indicates the
root of the depth-first search tree.
Yields chain (list) – A list of edges representing a chain. There is no guarantee on the orientation
of the edges in each chain (for example, if a chain includes the edge joining nodes 1 and 2, the
chain may include either (1, 2) or (2, 1)).
Raises NodeNotFound – If root is not in the graph G.
Notes
The worst-case running time of this implementation is linear in the number of nodes and number of edges1 .
References
3.9 Chordal
3.9.1 [Link].is_chordal
is_chordal(G)
Checks whether G is a chordal graph.
A graph is chordal if every cycle of length at least 4 has a chord (an edge joining two nodes not adjacent in the
cycle).
Parameters G (graph) – A NetworkX graph.
Returns chordal – True if G is a chordal graph and False otherwise.
Return type bool
Raises NetworkXError – The algorithm does not support DiGraph, MultiGraph and MultiDi-
Graph. If the input graph is an instance of one of these classes, a NetworkXError is raised.
Examples
>>> e = [
... (1, 2),
... (1, 3),
... (2, 3),
... (2, 4),
... (3, 4),
... (3, 5),
... (3, 6),
... (4, 5),
... (4, 6),
... (5, 6),
... ]
>>> G = [Link](e)
>>> nx.is_chordal(G)
True
Notes
The routine tries to go through every node following maximum cardinality search. It returns False when it finds
that the separator for any node is not a clique. Based on the algorithms in1 .
References
3.9.2 [Link].chordal_graph_cliques
chordal_graph_cliques(G)
Returns the set of maximal cliques of a chordal graph.
The algorithm breaks the graph in connected components and performs a maximum cardinality search in each
component to get the cliques.
Parameters G (graph) – A NetworkX graph
Returns cliques
Return type A set containing the maximal cliques in G.
Raises NetworkXError – The algorithm does not support DiGraph, MultiGraph and MultiDi-
Graph. If the input graph is an instance of one of these classes, a NetworkXError is raised.
The algorithm can only be applied to chordal graphs. If the input graph is found to be non-
chordal, a NetworkXError is raised.
1 R. E. Tarjan and M. Yannakakis, Simple linear-time algorithms to test chordality of graphs, test acyclicity of hypergraphs, and selectively
Examples
>>> e = [
... (1, 2),
... (1, 3),
... (2, 3),
... (2, 4),
... (3, 4),
... (3, 5),
... (3, 6),
... (4, 5),
... (4, 6),
... (5, 6),
... (7, 8),
... ]
>>> G = [Link](e)
>>> G.add_node(9)
>>> setlist = nx.chordal_graph_cliques(G)
3.9.3 [Link].chordal_graph_treewidth
chordal_graph_treewidth(G)
Returns the treewidth of the chordal graph G.
Parameters G (graph) – A NetworkX graph
Returns treewidth – The size of the largest clique in the graph minus one.
Return type int
Raises NetworkXError – The algorithm does not support DiGraph, MultiGraph and MultiDi-
Graph. If the input graph is an instance of one of these classes, a NetworkXError is raised.
The algorithm can only be applied to chordal graphs. If the input graph is found to be non-
chordal, a NetworkXError is raised.
Examples
>>> e = [
... (1, 2),
... (1, 3),
... (2, 3),
... (2, 4),
... (3, 4),
... (3, 5),
... (3, 6),
... (4, 5),
... (4, 6),
... (5, 6),
... (7, 8),
... ]
>>> G = [Link](e)
>>> G.add_node(9)
>>> nx.chordal_graph_treewidth(G)
3
References
3.9.4 [Link].complete_to_chordal_graph
complete_to_chordal_graph(G)
Return a copy of G completed to a chordal graph
Adds edges to a copy of G to create a chordal graph. A graph G=(V,E) is called chordal if for each cycle with
length bigger than 3, there exist two non-adjacent nodes connected by an edge (called a chord).
Parameters G (NetworkX graph) – Undirected graph
Returns
• H (NetworkX graph) – The chordal enhancement of G
• alpha (Dictionary) – The elimination ordering of nodes of G
Notes
There are different approaches to calculate the chordal enhancement of a graph. The algorithm used here is
called MCS-M and gives at least minimal (local) triangulation of graph. Note that this triangulation is not
necessarily a global minimum.
[Link]
References
Examples
3.9.5 [Link].find_induced_nodes
find_induced_nodes(G, s, t, treewidth_bound=9223372036854775807)
Returns the set of induced nodes in the path from s to t.
Parameters
• G (graph) – A chordal NetworkX graph
• s (node) – Source node to look for induced nodes
• t (node) – Destination node to look for induced nodes
• treewith_bound (float) – Maximum treewidth acceptable for the graph H. The search for
induced nodes will end as soon as the treewidth_bound is exceeded.
Returns Induced_nodes – The set of induced nodes in the path from s to t in G
Return type Set of nodes
Raises NetworkXError – The algorithm does not support DiGraph, MultiGraph and MultiDi-
Graph. If the input graph is an instance of one of these classes, a NetworkXError is raised.
The algorithm can only be applied to chordal graphs. If the input graph is found to be non-
chordal, a NetworkXError is raised.
Examples
>>> G = [Link]()
>>> G = [Link].path_graph(10)
>>> induced_nodes = nx.find_induced_nodes(G, 1, 9, 2)
>>> sorted(induced_nodes)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Notes
References
3.10 Clique
papers/volume9/elidan08a/[Link]
1 clique problem:: [Link]
3.10.1 [Link].enumerate_all_cliques
enumerate_all_cliques(G)
Returns all cliques in an undirected graph.
This function returns an iterator over cliques, each of which is a list of nodes. The iteration is ordered by
cardinality of the cliques: first all cliques of size one, then all cliques of size two, etc.
Parameters G (NetworkX graph) – An undirected graph.
Returns An iterator over cliques, each of which is a list of nodes in G. The cliques are ordered
according to size.
Return type iterator
Notes
To obtain a list of all cliques, use list(enumerate_all_cliques(G)). However, be aware that in the
worst-case, the length of this list can be exponential in the number of nodes in the graph (for example, when
the graph is the complete graph). This function avoids storing all cliques in memory by only keeping current
candidate node lists in memory during its search.
The implementation is adapted from the algorithm by Zhang, et al. (2005)1 to output all cliques discovered.
This algorithm ignores self-loops and parallel edges, since cliques are not conventionally defined with such
edges.
References
3.10.2 [Link].find_cliques
find_cliques(G)
Returns all maximal cliques in an undirected graph.
For each node v, a maximal clique for v is a largest complete subgraph containing v. The largest maximal clique
is sometimes called the maximum clique.
This function returns an iterator over cliques, each of which is a list of nodes. It is an iterative implementation,
so should not suffer from recursion depth issues.
Parameters G (NetworkX graph) – An undirected graph.
Returns An iterator over maximal cliques, each of which is a list of nodes in G. The order of cliques
is arbitrary.
Return type iterator
See also:
Memory-Intensive Applications in Systems Biology”. Supercomputing, 2005. Proceedings of the ACM/IEEE SC 2005 Conference, pp. 12, 12–18
Nov. 2005. <[Link]
Notes
To obtain a list of all maximal cliques, use list(find_cliques(G)). However, be aware that in the worst-
case, the length of this list can be exponential in the number of nodes in the graph. This function avoids storing
all cliques in memory by only keeping current candidate node lists in memory during its search.
This implementation is based on the algorithm published by Bron and Kerbosch (1973)1 , as adapted by Tomita,
Tanaka and Takahashi (2006)2 and discussed in Cazals and Karande (2008)3 . It essentially unrolls the re-
cursion used in the references to avoid issues of recursion stack depth (for a recursive implementation, see
find_cliques_recursive()).
This algorithm ignores self-loops and parallel edges, since cliques are not conventionally defined with such
edges.
References
3.10.3 [Link].make_max_clique_graph
make_max_clique_graph(G, create_using=None)
Returns the maximal clique graph of the given graph.
The nodes of the maximal clique graph of G are the cliques of G and an edge joins two cliques if the cliques are
not disjoint.
Parameters
• G (NetworkX graph)
• create_using (NetworkX graph constructor, optional (default=[Link])) – Graph type to
create. If graph instance, then cleared before populated.
Returns A graph whose nodes are the cliques of G and whose edges join two cliques if they are not
disjoint.
Return type NetworkX graph
Notes
import networkx as nx
G = nx.make_clique_bipartite(G)
cliques = [v for v in [Link]() if [Link][v]['bipartite'] == 0]
G = [Link](G, cliques)
G = nx.relabel_nodes(G, {-v: v - 1 for v in G})
experiments”, Theoretical Computer Science, Volume 363, Issue 1, Computing and Combinatorics, 10th Annual International Conference on
Computing and Combinatorics (COCOON 2004), 25 October 2006, Pages 28–42 <[Link]
3 F. Cazals, C. Karande, “A note on the problem of reporting maximal cliques”, Theoretical Computer Science, Volume 407, Issues 1–3, 6
3.10.4 [Link].make_clique_bipartite
3.10.5 [Link].graph_clique_number
graph_clique_number(G, cliques=None)
Returns the clique number of the graph.
The clique number of a graph is the size of the largest clique in the graph.
Parameters
• G (NetworkX graph) – An undirected graph.
• cliques (list) – A list of cliques, each of which is itself a list of nodes. If not specified, the
list of all cliques will be computed, as by find_cliques().
Returns The size of the largest clique in G.
Return type int
Notes
You should provide cliques if you have already computed the list of maximal cliques, in order to avoid an
exponential time search for maximal cliques.
3.10.6 [Link].graph_number_of_cliques
graph_number_of_cliques(G, cliques=None)
Returns the number of maximal cliques in the graph.
Parameters
• G (NetworkX graph) – An undirected graph.
• cliques (list) – A list of cliques, each of which is itself a list of nodes. If not specified, the
list of all cliques will be computed, as by find_cliques().
Returns The number of maximal cliques in G.
Return type int
Notes
You should provide cliques if you have already computed the list of maximal cliques, in order to avoid an
exponential time search for maximal cliques.
3.10.7 [Link].node_clique_number
3.10.8 [Link].number_of_cliques
3.10.9 [Link].cliques_containing_node
3.10.10 [Link].max_weight_clique
max_weight_clique(G, weight='weight')
Find a maximum weight clique in G.
A clique in a graph is a set of nodes such that every two distinct nodes are adjacent. The weight of a clique is
the sum of the weights of its nodes. A maximum weight clique of graph G is a clique C in G such that no clique
in G has weight greater than the weight of C.
Parameters
• G (NetworkX graph) – Undirected graph
• weight (string or None, optional (default=’weight’)) – The node attribute that holds the
integer value used as a weight. If None, then each node has weight 1.
Returns
• clique (list) – the nodes of a maximum weight clique
• weight (int) – the weight of a maximum weight clique
Notes
The implementation is recursive, and therefore it may run into recursion depth issues if G contains a clique
whose number of nodes is close to the recursion depth limit.
At each search node, the algorithm greedily constructs a weighted independent set cover of part of the graph in
order to find a small set of nodes on which to branch. The algorithm is very similar to the algorithm of Tavares
et al.1 , other than the fact that the NetworkX version does not use bitsets. This style of algorithm for maximum
weight clique (and maximum weight independent set, which is the same problem but on the complement graph)
has a decades-long history. See Algorithm B of Warren and Hicks2 and the references in that paper.
References
3.11 Clustering
3.11.1 [Link]
triangles(G, nodes=None)
Compute the number of triangles.
Finds the number of triangles that include a node as one vertex.
Parameters
• G (graph) – A networkx graph
• nodes (container of nodes, optional (default= all nodes in G)) – Compute triangles for nodes
in this container.
Returns out – Number of triangles keyed by node label.
1 Tavares, W.A., Neto, M.B.C., Rodrigues, C.D., Michelon, P.: Um algoritmo de branch and bound para o problema da clique máxima ponderada.
Examples
>>> G = nx.complete_graph(5)
>>> print([Link](G, 0))
6
>>> print([Link](G))
{0: 6, 1: 6, 2: 6, 3: 6, 4: 6}
>>> print(list([Link](G, (0, 1)).values()))
[6, 6]
Notes
When computing triangles for the entire graph each triangle is counted three times, once at each node. Self
loops are ignored.
3.11.2 [Link]
transitivity(G)
Compute graph transitivity, the fraction of all possible triangles present in G.
Possible triangles are identified by the number of “triads” (two edges with a shared vertex).
The transitivity is
#𝑡𝑟𝑖𝑎𝑛𝑔𝑙𝑒𝑠
𝑇 =3 .
#𝑡𝑟𝑖𝑎𝑑𝑠
Parameters G (graph)
Returns out – Transitivity
Return type float
Examples
>>> G = nx.complete_graph(5)
>>> print([Link](G))
1.0
3.11.3 [Link]
where 𝑇 (𝑢) is the number of triangles through node 𝑢 and 𝑑𝑒𝑔(𝑢) is the degree of 𝑢.
For weighted graphs, there are several ways to define clustering1 . the one used here is defined as the geometric
average of the subgraph edge weights2 ,
1 ∑︁
𝑐𝑢 = (𝑤
ˆ𝑢𝑣 𝑤 ˆ𝑣𝑤 )1/3 .
ˆ𝑢𝑤 𝑤
𝑑𝑒𝑔(𝑢)(𝑑𝑒𝑔(𝑢) − 1)) 𝑣𝑤
where 𝑇 (𝑢) is the number of directed triangles through node 𝑢, 𝑑𝑒𝑔 𝑡𝑜𝑡 (𝑢) is the sum of in degree and out degree
of 𝑢 and 𝑑𝑒𝑔 ↔ (𝑢) is the reciprocal degree of 𝑢.
Parameters
• G (graph)
• nodes (container of nodes, optional (default=all nodes in G)) – Compute clustering for
nodes in this container.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1.
Returns out – Clustering coefficient at specified nodes
Return type float, or dictionary
Examples
>>> G = nx.complete_graph(5)
>>> print([Link](G, 0))
1.0
>>> print([Link](G))
{0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}
Notes
References
3.11.4 [Link].average_clustering
Examples
>>> G = nx.complete_graph(5)
>>> print(nx.average_clustering(G))
1.0
Notes
This is a space saving routine; it might be faster to use the clustering function to get a list and then take the
average.
Self loops are ignored.
References
3.11.5 [Link].square_clustering
square_clustering(G, nodes=None)
Compute the squares clustering coefficient for nodes.
For each node return the fraction of possible squares that exist at the node1
∑︀𝑘𝑣 ∑︀𝑘𝑣
𝑤=𝑢+1 𝑞𝑣 (𝑢, 𝑤)
𝐶4 (𝑣) = ∑︀𝑘𝑣 ∑︀𝑢=1
𝑘𝑣
,
𝑢=1 𝑤=𝑢+1 [𝑎𝑣 (𝑢, 𝑤) + 𝑞𝑣 (𝑢, 𝑤)]
1 Pedro G. Lind, Marta C. González, and Hans J. Herrmann. 2005 Cycles and clustering in bipartite networks. Physical Review E (72) 056127.
where 𝑞𝑣 (𝑢, 𝑤) are the number of common neighbors of 𝑢 and 𝑤 other than 𝑣 (ie squares), and 𝑎𝑣 (𝑢, 𝑤) =
(𝑘𝑢 − (1 + 𝑞𝑣 (𝑢, 𝑤) + 𝜃𝑢𝑣 ))(𝑘𝑤 − (1 + 𝑞𝑣 (𝑢, 𝑤) + 𝜃𝑢𝑤 )), where 𝜃𝑢𝑤 = 1 if 𝑢 and 𝑤 are connected and 0
otherwise.
Parameters
• G (graph)
• nodes (container of nodes, optional (default=all nodes in G)) – Compute clustering for
nodes in this container.
Returns c4 – A dictionary keyed by node with the square clustering coefficient value.
Return type dictionary
Examples
>>> G = nx.complete_graph(5)
>>> print(nx.square_clustering(G, 0))
1.0
>>> print(nx.square_clustering(G))
{0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}
Notes
While 𝐶3 (𝑣) (triangle clustering) gives the probability that two neighbors of node v are connected with each
other, 𝐶4 (𝑣) is the probability that two neighbors of node v share a common neighbor different from v. This
algorithm can be applied to both bipartite and unipartite networks.
References
3.11.6 [Link].generalized_degree
generalized_degree(G, nodes=None)
Compute the generalized degree for nodes.
For each node, the generalized degree shows how many edges of given triangle multiplicity the node is connected
to. The triangle multiplicity of an edge is the number of triangles an edge participates in. The generalized degree
(0) (𝑁 −2) (𝑗)
of node 𝑖 can be written as a vector k𝑖 = (𝑘𝑖 , . . . , 𝑘𝑖 ) where 𝑘𝑖 is the number of edges attached to node
𝑖 that participate in 𝑗 triangles.
Parameters
• G (graph)
• nodes (container of nodes, optional (default=all nodes in G)) – Compute the generalized
degree for nodes in this container.
Returns out – Generalized degree of specified nodes. The Counter is keyed by edge triangle multi-
plicity.
Return type Counter, or dictionary of Counters
Examples
>>> G = nx.complete_graph(5)
>>> print(nx.generalized_degree(G, 0))
Counter({3: 4})
>>> print(nx.generalized_degree(G))
{0: Counter({3: 4}), 1: Counter({3: 4}), 2: Counter({3: 4}), 3: Counter({3: 4}),
˓→4: Counter({3: 4})}
>>> k1 = nx.generalized_degree(G, 0)
>>> sum([k * v for k, v in [Link]()]) / 2 == [Link](G, 0)
True
Notes
In a network of N nodes, the highest triangle multiplicty an edge can have is N-2.
The return value does not include a zero entry if no edges of a particular triangle multiplicity are present.
The number of triangles node 𝑖 is attached to can be recovered from the generalized degree k𝑖 =
(0) (𝑁 −2) (1) (2) (𝑁 −2)
(𝑘𝑖 , . . . , 𝑘𝑖 ) by (𝑘𝑖 + 2𝑘𝑖 + . . . + (𝑁 − 2)𝑘𝑖 )/2.
References
3.12 Coloring
greedy_color(G[, strategy, interchange]) Color a graph using various strategies of greedy graph
coloring.
equitable_color(G, num_colors) Provides equitable (r + 1)-coloring for nodes of G in O(r
* n^2) time if deg(G) <= r.
3.12.1 [Link].greedy_color
is the graph, and colors is a dictionary of the currently assigned colors, keyed by nodes.
The function must return an iterable over all the nodes in G.
If the strategy function is an iterator generator (that is, a function with yield statements),
keep in mind that the colors dictionary will be updated after each yield, since this
function chooses colors greedily.
If strategy is a string, it must be one of the following, each of which represents one of
the built-in strategy functions.
– 'largest_first'
– 'random_sequential'
– 'smallest_last'
– 'independent_set'
– 'connected_sequential_bfs'
– 'connected_sequential_dfs'
– 'connected_sequential' (alias for the previous strategy)
– 'saturation_largest_first'
– 'DSATUR' (alias for the previous strategy)
• interchange (bool) – Will use the color interchange algorithm described by3 if set to True.
Note that saturation_largest_first and independent_set do not work with
interchange. Furthermore, if you use interchange with your own strategy function, you
cannot rely on the values in the colors argument.
Returns
• A dictionary with keys representing nodes and values representing
• corresponding coloring.
Examples
>>> G = nx.cycle_graph(4)
>>> d = [Link].greedy_color(G, strategy="largest_first")
>>> d in [{0: 0, 1: 1, 2: 0, 3: 1}, {0: 1, 1: 0, 2: 1, 3: 0}]
True
45353-7.
References
3.12.2 [Link].equitable_color
equitable_color(G, num_colors)
Provides equitable (r + 1)-coloring for nodes of G in O(r * n^2) time if deg(G) <= r. The algorithm is described
in1 .
Attempts to color a graph using r colors, where no neighbors of a node can have same color as the node itself
and the number of nodes with each color differ by at most 1.
Parameters
• G (networkX graph) – The nodes of this graph will be colored.
• num_colors (number of colors to use) – This number must be at least one more than the
maximum degree of nodes in the graph.
Returns
• A dictionary with keys representing nodes and values representing
• corresponding coloring.
Examples
>>> G = nx.cycle_graph(4)
>>> d = [Link].equitable_color(G, num_colors=3)
>>> [Link].equitable_coloring.is_equitable(G, d)
True
References
Some node ordering strategies are provided for use with greedy_color().
3.12.3 [Link].strategy_connected_sequential
3.12.4 [Link].strategy_connected_sequential_dfs
strategy_connected_sequential_dfs(G, colors)
Returns an iterable over nodes in G in the order given by a depth-first traversal.
The generated sequence has the property that for each node except the first, at least one neighbor appeared
earlier in the sequence.
G is a NetworkX graph. colors is ignored.
3.12.5 [Link].strategy_connected_sequential_bfs
strategy_connected_sequential_bfs(G, colors)
Returns an iterable over nodes in G in the order given by a breadth-first traversal.
The generated sequence has the property that for each node except the first, at least one neighbor appeared
earlier in the sequence.
G is a NetworkX graph. colors is ignored.
3.12.6 [Link].strategy_independent_set
strategy_independent_set(G, colors)
Uses a greedy independent set removal strategy to determine the colors.
This function updates colors in-place and return None, unlike the other strategy functions in this module.
This algorithm repeatedly finds and removes a maximal independent set, assigning each node in the set an
unused color.
G is a NetworkX graph.
This strategy is related to strategy_smallest_last(): in that strategy, an independent set of size one is
chosen at each step instead of a maximal independent set.
3.12.7 [Link].strategy_largest_first
strategy_largest_first(G, colors)
Returns a list of the nodes of G in decreasing order by degree.
G is a NetworkX graph. colors is ignored.
3.12.8 [Link].strategy_random_sequential
3.12.9 [Link].strategy_saturation_largest_first
strategy_saturation_largest_first(G, colors)
Iterates over all the nodes of G in “saturation order” (also known as “DSATUR”).
G is a NetworkX graph. colors is a dictionary mapping nodes of G to colors, for those nodes that have already
been colored.
3.12.10 [Link].strategy_smallest_last
strategy_smallest_last(G, colors)
Returns a deque of the nodes of G, “smallest” last.
Specifically, the degrees of each node are tracked in a bucket queue. From this, the node of minimum degree is
repeatedly popped from the graph, updating its neighbors’ degrees.
G is a NetworkX graph. colors is ignored.
This implementation of the strategy runs in 𝑂(𝑛 + 𝑚) time (ignoring polylogarithmic factors), where 𝑛 is the
number of nodes and 𝑚 is the number of edges.
This strategy is related to strategy_independent_set(): if we interpret each node removed as an
independent set of size one, then this strategy chooses an independent set of size one instead of a maximal
independent set.
3.13 Communicability
Communicability.
3.13.1 [Link].communicability_alg.communicability
communicability(G)
Returns communicability between all pairs of nodes in G.
The communicability between pairs of nodes in G is the sum of walks of different lengths starting at node u and
ending at node v.
Parameters G (graph)
Returns comm – Dictionary of dictionaries keyed by nodes with communicability as the value.
Return type dictionary of dictionaries
Raises NetworkXError – If the graph is not undirected and simple.
See also:
Notes
This algorithm uses a spectral decomposition of the adjacency matrix. Let G=(V,E) be a simple undirected
graph. Using the connection between the powers of the adjacency matrix and the number of walks in the graph,
the communicability between nodes u and v based on the graph spectrum is1
𝑛
∑︁
𝐶(𝑢, 𝑣) = 𝜑𝑗 (𝑢)𝜑𝑗 (𝑣)𝑒𝜆𝑗 ,
𝑗=1
where phi_{j}(u) is the urm{th} element of the jrm{th} orthonormal eigenvector of the adjacency
matrix associated with the eigenvalue lambda_{j}.
References
Examples
>>> G = [Link]([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
>>> c = [Link](G)
3.13.2 [Link].communicability_alg.communicability_exp
communicability_exp(G)
Returns communicability between all pairs of nodes in G.
Communicability between pair of node (u,v) of node in G is the sum of walks of different lengths starting at
node u and ending at node v.
Parameters G (graph)
Returns comm – Dictionary of dictionaries keyed by nodes with communicability as the value.
Return type dictionary of dictionaries
1 Ernesto Estrada, Naomichi Hatano, “Communicability in complex networks”, Phys. Rev. E 77, 036111 (2008). [Link]
Notes
References
Examples
>>> G = [Link]([(0, 1), (1, 2), (1, 5), (5, 4), (2, 4), (2, 3), (4, 3), (3, 6)])
>>> c = nx.communicability_exp(G)
3.14 Communities
1 Ernesto Estrada, Naomichi Hatano, “Communicability in complex networks”, Phys. Rev. E 77, 036111 (2008). [Link]
3.14.1 Bipartitions
[Link].kernighan_lin.kernighan_lin_bisection
References
3.14.2 K-Clique
k_clique_communities(G, k[, cliques]) Find k-clique communities in graph using the percola-
tion method.
[Link].k_clique_communities
k_clique_communities(G, k, cliques=None)
Find k-clique communities in graph using the percolation method.
A k-clique community is the union of all cliques of size k that can be reached through adjacent (sharing k-1
nodes) k-cliques.
Parameters
• G (NetworkX graph)
• k (int) – Size of smallest clique
Examples
References
[Link].modularity_max.greedy_modularity_communities
greedy_modularity_communities(G, weight=None)
Find communities in graph using Clauset-Newman-Moore greedy modularity maximization. This method cur-
rently supports the Graph class and does not consider edge weights.
Greedy modularity maximization begins with each node in its own community and joins the pair of communities
that most increases modularity until no such pair exists.
Parameters G (NetworkX graph)
Returns
Return type Yields sets of nodes, one for each community.
Examples
References
[Link].modularity_max._naive_greedy_modularity_communities
_naive_greedy_modularity_communities(G)
Find communities in graph using the greedy modularity maximization. This implementation is O(n^4), much
slower than alternatives, but it is provided as an easy-to-understand reference implementation.
[Link].lukes_partitioning
References
[Link].label_propagation.asyn_lpa_communities
Notes
References
[Link].label_propagation.label_propagation_communities
label_propagation_communities(G)
Generates community sets determined by label propagation
Finds communities in G using a semi-synchronous label propagation method[1]_. This method combines the
advantages of both the synchronous and asynchronous models. Not implemented for directed graphs.
Parameters G (graph) – An undirected NetworkX graph.
Yields communities (generator) – Yields sets of the nodes in each community.
Raises NetworkXNotImplemented – If the graph is directed
References
[Link].asyn_fluid.asyn_fluidc
Notes
References
[Link]
coverage(G, partition)
Returns the coverage of a partition.
The coverage of a partition is the ratio of the number of intra-community edges to the total number of edges in
the graph.
Parameters
• G (NetworkX graph)
• partition (sequence) – Partition of the nodes of G, represented as a sequence of sets of
nodes. Each block of the partition represents a community.
Returns The coverage of the partition, as defined above.
Return type float
Raises NetworkXError – If partition is not a valid partition of the nodes of G.
Notes
References
[Link]
where 𝑚 is the number of edges, 𝐴 is the adjacency matrix of G, 𝑘𝑖 is the degree of 𝑖 and 𝛿(𝑐𝑖 , 𝑐𝑗 ) is 1 if 𝑖 and 𝑗
are in the same community and 0 otherwise.
According to2 (and verified by some algebra) this can be reduced to
𝑛
[︃ (︂ )︂2 ]︃
∑︁ 𝐿𝑐 𝑘𝑐
𝑄= −
𝑐=1
𝑚 2𝑚
where the sum iterates over all communities 𝑐, 𝑚 is the number of edges, 𝐿𝑐 is the number of intra-community
links for community 𝑐, 𝑘𝑐 is the sum of degrees of the nodes in community 𝑐.
The second formula is the one actually used in calculation of the modularity.
Parameters
• G (NetworkX Graph)
• communities (list or iterable of set of nodes) – These node sets must represent a partition
of G’s nodes.
• weight (string or None, optional (default=”weight”)) – The edge attribute that holds the
numerical value used as a weight. If None or an edge does not have that attribute, then that
edge has weight 1.
Returns Q – The modularity of the paritition.
Return type float
Raises NotAPartition – If communities is not a partition of the nodes of G.
Examples
1M. E. J. Newman Networks: An Introduction, page 224. Oxford University Press, 2011.
2Clauset, Aaron, Mark EJ Newman, and Cristopher Moore. “Finding community structure in very large networks.” Physical review E 70.6
(2004). <[Link]
References
[Link]
performance(G, partition)
Returns the performance of a partition.
The performance of a partition is the ratio of the number of intra-community edges plus inter-community non-
edges with the total number of potential edges.
Parameters
• G (NetworkX graph) – A simple graph (directed or undirected).
• partition (sequence) – Partition of the nodes of G, represented as a sequence of sets of
nodes. Each block of the partition represents a community.
Returns The performance of the partition, as defined above.
Return type float
Raises NetworkXError – If partition is not a valid partition of the nodes of G.
References
[Link].girvan_newman
girvan_newman(G, most_valuable_edge=None)
Finds communities in a graph using the Girvan–Newman method.
Parameters
• G (NetworkX graph)
• most_valuable_edge (function) – Function that takes a graph as input and outputs an edge.
The edge returned by this function will be recomputed and removed at each iteration of the
algorithm.
If not specified, the edge with the highest networkx.
edge_betweenness_centrality() will be used.
Returns Iterator over tuples of sets of nodes in G. Each set of node is a community, each tuple is a
sequence of communities at a particular level of the algorithm.
Return type iterator
Examples
To stop getting tuples of communities once the number of communities is greater than k, use itertools.
takewhile():
>>> import itertools
>>> G = nx.path_graph(8)
>>> k = 4
>>> comp = girvan_newman(G)
>>> limited = [Link](lambda c: len(c) <= k, comp)
>>> for communities in limited:
... print(tuple(sorted(c) for c in communities))
...
([0, 1, 2, 3], [4, 5, 6, 7])
([0, 1], [2, 3], [4, 5, 6, 7])
([0, 1], [2, 3], [4, 5], [6, 7])
To utilize edge weights when choosing an edge with, for example, the highest betweenness centrality:
>>> from networkx import edge_betweenness_centrality as betweenness
>>> def most_central_edge(G):
... centrality = betweenness(G, weight="weight")
... return max(centrality, key=[Link])
...
>>> G = nx.path_graph(10)
(continues on next page)
To specify a different ranking algorithm for edges, use the most_valuable_edge keyword argument:
Notes
The Girvan–Newman algorithm detects communities by progressively removing edges from the original graph.
The algorithm removes the “most valuable” edge, traditionally the edge with the highest betweenness centrality,
at each step. As the graph breaks down into pieces, the tightly knit community structure is exposed and the
result can be depicted as a dendrogram.
[Link].community_utils.is_partition
is_partition(G, communities)
Returns True if communities is a partition of the nodes of G.
A partition of a universe set is a family of pairwise disjoint sets whose union is the entire universe set.
Parameters
• G (NetworkX graph.)
• communities (list or iterable of sets of nodes) – If not a list, the iterable is converted inter-
nally to a list. If it is an iterator it is exhausted.
3.15 Components
3.15.1 Connectivity
[Link].is_connected
is_connected(G)
Returns True if the graph is connected, False otherwise.
Parameters G (NetworkX Graph) – An undirected graph.
Returns connected – True if the graph is connected, false otherwise.
Return type bool
Raises NetworkXNotImplemented – If G is directed.
Examples
>>> G = nx.path_graph(4)
>>> print(nx.is_connected(G))
True
See also:
is_strongly_connected(), is_weakly_connected(), is_semiconnected(),
is_biconnected(), connected_components()
Notes
[Link].number_connected_components
number_connected_components(G)
Returns the number of connected components.
Parameters G (NetworkX graph) – An undirected graph.
Returns n – Number of connected components
Return type integer
See also:
connected_components(), number_weakly_connected_components(),
number_strongly_connected_components()
Notes
[Link].connected_components
connected_components(G)
Generate connected components.
Parameters G (NetworkX graph) – An undirected graph
Returns comp – A generator of sets of nodes, one for each component of G.
Return type generator of sets
Raises NetworkXNotImplemented – If G is directed.
Examples
>>> G = nx.path_graph(4)
>>> nx.add_path(G, [10, 11, 12])
>>> [len(c) for c in sorted(nx.connected_components(G), key=len, reverse=True)]
[4, 3]
If you only want the largest connected component, it’s more efficient to use max instead of sort.
See also:
strongly_connected_components(), weakly_connected_components()
Notes
[Link].node_connected_component
node_connected_component(G, n)
Returns the set of nodes in the component of graph containing node n.
Parameters
• G (NetworkX Graph) – An undirected graph.
• n (node label) – A node in G
Returns comp – A set of nodes in the component of G containing node n.
Return type set
Raises NetworkXNotImplemented – If G is directed.
See also:
connected_components()
Notes
[Link].is_strongly_connected
is_strongly_connected(G)
Test directed graph for strong connectivity.
A directed graph is strongly connected if and only if every vertex in the graph is reachable from every other
vertex.
Parameters G (NetworkX Graph) – A directed graph.
Returns connected – True if the graph is strongly connected, False otherwise.
Return type bool
Raises NetworkXNotImplemented – If G is undirected.
See also:
is_weakly_connected(), is_semiconnected(), is_connected(), is_biconnected(),
strongly_connected_components()
Notes
[Link].number_strongly_connected_components
number_strongly_connected_components(G)
Returns number of strongly connected components in graph.
Parameters G (NetworkX graph) – A directed graph.
Returns n – Number of strongly connected components
Return type integer
Raises NetworkXNotImplemented – If G is undirected.
See also:
strongly_connected_components(), number_connected_components(),
number_weakly_connected_components()
Notes
[Link].strongly_connected_components
strongly_connected_components(G)
Generate nodes in strongly connected components of graph.
Parameters G (NetworkX Graph) – A directed graph.
Returns comp – A generator of sets of nodes, one for each strongly connected component of G.
Return type generator of sets
Raises NetworkXNotImplemented – If G is undirected.
Examples
... ]
[4, 3]
If you only want the largest component, it’s more efficient to use max instead of sort.
See also:
connected_components(), weakly_connected_components(),
kosaraju_strongly_connected_components()
Notes
References
[Link].strongly_connected_components_recursive
strongly_connected_components_recursive(G)
Generate nodes in strongly connected components of graph.
Recursive version of algorithm.
Parameters G (NetworkX Graph) – A directed graph.
Returns comp – A generator of sets of nodes, one for each strongly connected component of G.
Return type generator of sets
Raises NetworkXNotImplemented – If G is undirected.
Examples
If you only want the largest component, it’s more efficient to use max instead of sort.
To create the induced subgraph of the components use: >>> S = [[Link](c).copy() for c in
nx.weakly_connected_components(G)]
See also:
connected_components()
Notes
References
[Link].kosaraju_strongly_connected_components
kosaraju_strongly_connected_components(G, source=None)
Generate nodes in strongly connected components of graph.
Parameters G (NetworkX Graph) – A directed graph.
Returns comp – A genrator of sets of nodes, one for each strongly connected component of G.
Return type generator of sets
Raises NetworkXNotImplemented – If G is undirected.
Examples
If you only want the largest component, it’s more efficient to use max instead of sort.
See also:
strongly_connected_components()
Notes
[Link]
condensation(G, scc=None)
Returns the condensation of G.
The condensation of G is the graph with each of the strongly connected components contracted into a single
node.
Parameters
• G (NetworkX DiGraph) – A directed graph.
• scc (list or generator (optional, default=None)) – Strongly connected components. If pro-
vided, the elements in scc must partition the nodes in G. If not provided, it will be calculated
as scc=nx.strongly_connected_components(G).
Returns C – The condensation graph C of G. The node labels are integers corresponding to the index
of the component in the list of strongly connected components of G. C has a graph attribute
named ‘mapping’ with a dictionary mapping the original nodes to the nodes in C to which they
belong. Each node in C also has a node attribute ‘members’ with the set of original nodes in G
that form the SCC that the node in C represents.
Return type NetworkX DiGraph
Raises NetworkXNotImplemented – If G is undirected.
Notes
After contracting all strongly connected components to a single node, the resulting graph is a directed acyclic
graph.
[Link].is_weakly_connected
is_weakly_connected(G)
Test directed graph for weak connectivity.
A directed graph is weakly connected if and only if the graph is connected when the direction of the edge
between nodes is ignored.
Note that if a graph is strongly connected (i.e. the graph is connected even when we account for directionality),
it is by definition weakly connected as well.
Parameters G (NetworkX Graph) – A directed graph.
Returns connected – True if the graph is weakly connected, False otherwise.
Return type bool
Raises NetworkXNotImplemented – If G is undirected.
See also:
is_strongly_connected(), is_semiconnected(), is_connected(), is_biconnected(),
weakly_connected_components()
Notes
[Link].number_weakly_connected_components
number_weakly_connected_components(G)
Returns the number of weakly connected components in G.
Parameters G (NetworkX graph) – A directed graph.
Returns n – Number of weakly connected components
Return type integer
Raises NetworkXNotImplemented – If G is undirected.
See also:
weakly_connected_components(), number_connected_components(),
number_strongly_connected_components()
Notes
[Link].weakly_connected_components
weakly_connected_components(G)
Generate weakly connected components of G.
Parameters G (NetworkX graph) – A directed graph
Returns comp – A generator of sets of nodes, one for each weakly connected component of G.
Return type generator of sets
Raises NetworkXNotImplemented – If G is undirected.
Examples
If you only want the largest component, it’s more efficient to use max instead of sort:
See also:
connected_components(), strongly_connected_components()
Notes
[Link].is_attracting_component
is_attracting_component(G)
Returns True if G consists of a single attracting component.
Parameters G (DiGraph, MultiDiGraph) – The graph to be analyzed.
Returns attracting – True if G has a single attracting component. Otherwise, False.
Return type bool
Raises NetworkXNotImplemented – If the input graph is undirected.
See also:
attracting_components(), number_attracting_components()
[Link].number_attracting_components
number_attracting_components(G)
Returns the number of attracting components in G.
Parameters G (DiGraph, MultiDiGraph) – The graph to be analyzed.
Returns n – The number of attracting components in G.
Return type int
Raises NetworkXNotImplemented – If the input graph is undirected.
See also:
attracting_components(), is_attracting_component()
[Link].attracting_components
attracting_components(G)
Generates the attracting components in G.
An attracting component in a directed graph G is a strongly connected component with the property that a
random walker on the graph will never leave the component, once it enters the component.
The nodes in attracting components can also be thought of as recurrent nodes. If a random walker enters the
attractor containing the node, then the node will be visited infinitely often.
[Link].is_biconnected
is_biconnected(G)
Returns True if the graph is biconnected, False otherwise.
A graph is biconnected if, and only if, it cannot be disconnected by removing only one node (and all edges
incident on that node). If removing a node increases the number of disconnected components in the graph, that
node is called an articulation point, or cut vertex. A biconnected graph has no articulation points.
Parameters G (NetworkX Graph) – An undirected graph.
Returns biconnected – True if the graph is biconnected, False otherwise.
Return type bool
Raises NetworkXNotImplemented – If the input graph is not undirected.
Examples
>>> G = nx.path_graph(4)
>>> print(nx.is_biconnected(G))
False
>>> G.add_edge(0, 3)
>>> print(nx.is_biconnected(G))
True
See also:
biconnected_components(), articulation_points(), biconnected_component_edges(),
is_strongly_connected(), is_weakly_connected(), is_connected(),
is_semiconnected()
Notes
The algorithm to find articulation points and biconnected components is implemented using a non-recursive
depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node n
is an articulation point if, and only if, there exists a subtree rooted at n such that there is no back edge from
any successor of n that links to a predecessor of n in the DFS tree. By keeping track of all the edges traversed
by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed
consecutively between articulation points.
References
[Link].biconnected_components
biconnected_components(G)
Returns a generator of sets of nodes, one set for each biconnected component of the graph
Biconnected components are maximal subgraphs such that the removal of a node (and all edges incident on that
node) will not disconnect the subgraph. Note that nodes may be part of more than one biconnected component.
Those nodes are articulation points, or cut vertices. The removal of articulation points will increase the number
of connected components of the graph.
Notice that by convention a dyad is considered a biconnected component.
Parameters G (NetworkX Graph) – An undirected graph.
Returns nodes – Generator of sets of nodes, one set for each biconnected component.
Return type generator
Raises NetworkXNotImplemented – If the input graph is not undirected.
See also:
Examples
>>> G = nx.lollipop_graph(5, 1)
>>> print(nx.is_biconnected(G))
False
>>> bicomponents = list(nx.biconnected_components(G))
>>> len(bicomponents)
2
>>> G.add_edge(0, 5)
>>> print(nx.is_biconnected(G))
True
>>> bicomponents = list(nx.biconnected_components(G))
>>> len(bicomponents)
1
You can generate a sorted list of biconnected components, largest first, using sort.
>>> G.remove_edge(0, 5)
>>> [len(c) for c in sorted(nx.biconnected_components(G), key=len, reverse=True)]
[5, 2]
If you only want the largest connected component, it’s more efficient to use max instead of sort.
Notes
The algorithm to find articulation points and biconnected components is implemented using a non-recursive
depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node n
is an articulation point if, and only if, there exists a subtree rooted at n such that there is no back edge from
any successor of n that links to a predecessor of n in the DFS tree. By keeping track of all the edges traversed
by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed
consecutively between articulation points.
References
[Link].biconnected_component_edges
biconnected_component_edges(G)
Returns a generator of lists of edges, one list for each biconnected component of the input graph.
Biconnected components are maximal subgraphs such that the removal of a node (and all edges incident on that
node) will not disconnect the subgraph. Note that nodes may be part of more than one biconnected compo-
nent. Those nodes are articulation points, or cut vertices. However, each edge belongs to one, and only one,
biconnected component.
Notice that by convention a dyad is considered a biconnected component.
Parameters G (NetworkX Graph) – An undirected graph.
Returns edges – Generator of lists of edges, one list for each bicomponent.
Return type generator of lists
Raises NetworkXNotImplemented – If the input graph is not undirected.
Examples
>>> G = nx.barbell_graph(4, 2)
>>> print(nx.is_biconnected(G))
False
>>> bicomponents_edges = list(nx.biconnected_component_edges(G))
>>> len(bicomponents_edges)
5
>>> G.add_edge(2, 8)
>>> print(nx.is_biconnected(G))
True
>>> bicomponents_edges = list(nx.biconnected_component_edges(G))
>>> len(bicomponents_edges)
1
See also:
is_biconnected(), biconnected_components(), articulation_points()
Notes
The algorithm to find articulation points and biconnected components is implemented using a non-recursive
depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node n
is an articulation point if, and only if, there exists a subtree rooted at n such that there is no back edge from
any successor of n that links to a predecessor of n in the DFS tree. By keeping track of all the edges traversed
by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed
consecutively between articulation points.
References
[Link].articulation_points
articulation_points(G)
Yield the articulation points, or cut vertices, of a graph.
An articulation point or cut vertex is any node whose removal (along with all its incident edges) increases the
number of connected components of a graph. An undirected connected graph without articulation points is
biconnected. Articulation points belong to more than one biconnected component of a graph.
Notice that by convention a dyad is considered a biconnected component.
Parameters G (NetworkX Graph) – An undirected graph.
Yields node – An articulation point in the graph.
Raises NetworkXNotImplemented – If the input graph is not undirected.
Examples
>>> G = nx.barbell_graph(4, 2)
>>> print(nx.is_biconnected(G))
False
>>> len(list(nx.articulation_points(G)))
4
>>> G.add_edge(2, 8)
>>> print(nx.is_biconnected(G))
True
>>> len(list(nx.articulation_points(G)))
0
See also:
is_biconnected(), biconnected_components(), biconnected_component_edges()
Notes
The algorithm to find articulation points and biconnected components is implemented using a non-recursive
depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node n
is an articulation point if, and only if, there exists a subtree rooted at n such that there is no back edge from
any successor of n that links to a predecessor of n in the DFS tree. By keeping track of all the edges traversed
by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed
consecutively between articulation points.
References
3.15.6 Semiconnectedness
[Link].is_semiconnected
is_semiconnected(G, topo_order=None)
Returns True if the graph is semiconnected, False otherwise.
A graph is semiconnected if, and only if, for any pair of nodes, either one is reachable from the other, or they
are mutually reachable.
Parameters
• G (NetworkX graph) – A directed graph.
• topo_order (list or tuple, optional) – A topological order for G (if None, the function will
compute one)
Returns semiconnected – True if the graph is semiconnected, False otherwise.
Return type bool
Raises
• NetworkXNotImplemented – If the input graph is undirected.
Examples
See also:
is_strongly_connected(), is_weakly_connected(), is_connected(),
is_biconnected()
3.16 Connectivity
3.16.1 Edge-augmentation
[Link].edge_augmentation.k_edge_augmentation
Notes
Example
Example
[Link].edge_augmentation.is_k_edge_connected
is_k_edge_connected(G, k)
Tests to see if a graph is k-edge-connected.
Is it impossible to disconnect the graph by removing fewer than k edges? If so, then G is k-edge-connected.
Parameters
• G (NetworkX graph) – An undirected graph.
• k (integer) – edge connectivity to test for
Returns True if G is k-edge-connected.
Return type boolean
See also:
is_locally_k_edge_connected()
Example
>>> G = nx.barbell_graph(10, 0)
>>> nx.is_k_edge_connected(G, k=1)
True
>>> nx.is_k_edge_connected(G, k=2)
False
[Link].edge_augmentation.is_locally_k_edge_connected
is_locally_k_edge_connected(G, s, t, k)
Tests to see if an edge in a graph is locally k-edge-connected.
Is it impossible to disconnect s and t by removing fewer than k edges? If so, then s and t are locally k-edge-
connected in G.
Parameters
• G (NetworkX graph) – An undirected graph.
• s (node) – Source node
• t (node) – Target node
• k (integer) – local edge connectivity for nodes s and t
Returns True if s and t are locally k-edge-connected in G.
Return type boolean
See also:
is_k_edge_connected()
Example
3.16.2 K-edge-components
[Link].edge_kcomponents.k_edge_components
k_edge_components(G, k)
Generates nodes in each maximal k-edge-connected component in G.
Parameters
• G (NetworkX graph)
• k (Integer) – Desired edge connectivity
Returns k_edge_components – will have k-edge-connectivity in the graph G.
Return type a generator of k-edge-ccs. Each set of returned nodes
See also:
local_edge_connectivity()
k_edge_subgraphs() similar to this function, but the subgraph defined by the nodes must also have k-
edge-connectivity.
k_components() similar to this function, but uses node-connectivity instead of edge-connectivity
Raises
• NetworkXNotImplemented – If the input graph is a multigraph.
• ValueError: – If k is less than 1
Notes
Attempts to use the most efficient implementation available based on k. If k=1, this is simply simply connected
components for directed graphs and connected components for undirected graphs. If k=2 on an efficient bridge
connected component algorithm from _[1] is run based on the chain decomposition. Otherwise, the algorithm
from _[2] is used.
Example
References
[Link].edge_kcomponents.k_edge_subgraphs
k_edge_subgraphs(G, k)
Generates nodes in each maximal k-edge-connected subgraph in G.
Parameters
• G (NetworkX graph)
• k (Integer) – Desired edge connectivity
Returns k_edge_subgraphs – Each k-edge-subgraph is a maximal set of nodes that defines a sub-
graph of G that is k-edge-connected.
Return type a generator of k-edge-subgraphs
See also:
edge_connectivity()
k_edge_components() similar to this function, but nodes only need to have k-edge-connctivity within the
graph G and the subgraphs might not be k-edge-connected.
Raises
• NetworkXNotImplemented – If the input graph is a multigraph.
• ValueError: – If k is less than 1
Notes
Attempts to use the most efficient implementation available based on k. If k=1, or k=2 and the graph is undi-
rected, then this simply calls k_edge_components. Otherwise the algorithm from _[1] is used.
Example
References
[Link].edge_kcomponents.bridge_components
bridge_components(G)
Finds all bridge-connected components G.
Parameters G (NetworkX undirected graph)
Returns bridge_components
Return type a generator of 2-edge-connected components
See also:
k_edge_subgraphs() this function is a special case for an undirected graph where k=2.
biconnected_components() similar to this function, but is defined using 2-node-connectivity instead of
2-edge-connectivity.
Notes
Example
>>> # The barbell graph with parameter zero has a single bridge
>>> G = nx.barbell_graph(5, 0)
>>> from [Link].edge_kcomponents import bridge_
˓→components
[Link].edge_kcomponents.EdgeComponentAuxGraph
class EdgeComponentAuxGraph
A simple algorithm to find all k-edge-connected components in a graph.
Constructing the AuxillaryGraph (which may take some time) allows for the k-edge-ccs to be found in linear
time for arbitrary k.
Notes
This implementation is based on1 . The idea is to construct an auxiliary graph from which the k-edge-ccs can be
extracted in linear time. The auxiliary graph is constructed in 𝑂(|𝑉 | · 𝐹 ) operations, where F is the complexity
of max flow. Querying the components takes an additional 𝑂(|𝑉 |) operations. This algorithm can be slow for
large graphs, but it handles an arbitrary k and works for both directed and undirected inputs.
The undirected case for k=1 is exactly connected components. The undirected case for k=2 is exactly bridge
connected components. The directed case for k=1 is exactly strongly connected components.
1 Wang, Tianhao, et al. (2015) A simple algorithm for finding all k-edge-connected components. [Link]
1371/[Link].0136264
References
Example
Example
__init__()
Initialize self. See help(type(self)) for accurate signature.
Methods
3.16.3 K-node-components
[Link].k_components
k_components(G, flow_func=None)
Returns the k-component structure of a graph G.
A k-component is a maximal subgraph of a graph G that has, at least, node connectivity k: we need to remove at
least k nodes to break it into more components. k-components have an inherent hierarchical structure because
they are nested in terms of connectivity: a connected graph can contain several 2-components, each of which
can contain one or more 3-components, and so forth.
Parameters
• G (NetworkX graph)
• flow_func (function) – Function to perform the underlying flow computations. Default value
edmonds_karp(). This function performs better in sparse graphs with right tailed degree
distributions. shortest_augmenting_path() will perform better in denser graphs.
Returns k_components – Dictionary with all connectivity levels k in the input Graph as keys and a
list of sets of nodes that form a k-component of level k as values.
Return type dict
Raises NetworkXNotImplemented – If the input graph is directed.
Examples
Notes
Moody and White1 (appendix A) provide an algorithm for identifying k-components in a graph, which is
based on Kanevsky’s algorithm2 for finding all minimum-size node cut-sets of a graph (implemented in
all_node_cuts() function):
1. Compute node connectivity, k, of the input graph G.
2. Identify all k-cutsets at the current level of connectivity using Kanevsky’s algorithm.
3. Generate new graph components based on the removal of these cutsets. Nodes in a cutset belong to both
sides of the induced cut.
4. If the graph is neither complete nor trivial, return to 1; else end.
This implementation also uses some heuristics (see3 for details) to speed up the computation.
See also:
node_connectivity(), all_node_cuts()
biconnected_components() special case of this function when k=2
k_edge_components() similar to this function, but uses edge-connectivity instead of node-connectivity
References
3.16.4 K-node-cutsets
[Link].all_node_cuts
doi/10.1002/net.3230230604/abstract
3 Torrents, J. and F. Ferraro (2015). Structural Cohesion: Visualization and Heuristics for Fast Computation. [Link]
1 Kanevsky, A. (1993). Finding all minimum-size separating vertex sets in a graph. Networks 23(6), 533–541. [Link]
doi/10.1002/net.3230230604/abstract
edmonds_karp. This function performs better in sparse graphs with right tailed degree dis-
tributions. shortest_augmenting_path will perform better in denser graphs.
Returns cuts – Each node cutset has cardinality equal to the node connectivity of the input graph.
Return type a generator of node cutsets
Examples
Notes
This implementation is based on the sequential algorithm for finding all minimum-size separating vertex sets in
a graph1 . The main idea is to compute minimum cuts using local maximum flow computations among a set of
nodes of highest degree and all other non-adjacent nodes in the Graph. Once we find a minimum cut, we add an
edge between the high degree node and the target node of the local maximum flow computation to make sure
that we will not find that minimum cut again.
See also:
node_connectivity(), edmonds_karp(), shortest_augmenting_path()
References
edge_disjoint_paths(G, s, t[, flow_func, . . . ]) Returns the edges disjoint paths between source and tar-
get.
node_disjoint_paths(G, s, t[, flow_func, . . . ]) Computes node disjoint paths between source and tar-
get.
[Link].disjoint_paths.edge_disjoint_paths
Examples
We use in this example the platonic icosahedral graph, which has node edge connectivity 5, thus there are 5 edge
disjoint paths between any pair of nodes.
>>> G = nx.icosahedral_graph()
>>> len(list(nx.edge_disjoint_paths(G, 0, 6)))
5
If you need to compute edge disjoint paths on several pairs of nodes in the same graph, it is recommended that
you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for edge connectivity,
and the residual network for the underlying maximum flow computation.
Example of how to compute edge disjoint paths among all pairs of nodes of the platonic icosahedral graph
reusing the data structures.
You can also use alternative flow algorithms for computing edge disjoint paths. For instance, in dense
networks the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp() which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
Notes
This is a flow based implementation of edge disjoint paths. We compute the maximum flow between source and
target on an auxiliary directed network. The saturated edges in the residual network after running the maximum
flow algorithm correspond to edge disjoint paths between source and target in the original network. This function
handles both directed and undirected graphs, and can use all flow algorithms from NetworkX flow package.
[Link].disjoint_paths.node_disjoint_paths
port the cutoff parameter, and will terminate when the flow value reaches or exceeds the
cutoff. Other algorithms will ignore this parameter. Default value: None.
• auxiliary (NetworkX DiGraph) – Auxiliary digraph to compute flow based node connectiv-
ity. It has to have a graph attribute called mapping with a dictionary mapping node names
in G and in the auxiliary digraph. If provided it will be reused instead of recreated. Default
value: None.
• residual (NetworkX DiGraph) – Residual network to compute maximum flow. If provided
it will be reused instead of recreated. Default value: None.
Returns paths – Generator of node disjoint paths.
Return type generator
Raises
• NetworkXNoPath – If there is no path between source and target.
• NetworkXError – If source or target are not in the graph G.
Examples
We use in this example the platonic icosahedral graph, which has node node connectivity 5, thus there are 5
node disjoint paths between any pair of non neighbor nodes.
>>> G = nx.icosahedral_graph()
>>> len(list(nx.node_disjoint_paths(G, 0, 6)))
5
If you need to compute node disjoint paths between several pairs of nodes in the same graph, it is recommended
that you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for node con-
nectivity and node cuts, and the residual network for the underlying maximum flow computation.
Example of how to compute node disjoint paths reusing the data structures:
You can also use alternative flow algorithms for computing node disjoint paths. For instance, in dense
networks the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp() which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
Notes
This is a flow based implementation of node disjoint paths. We compute the maximum flow between source
and target on an auxiliary directed network. The saturated edges in the residual network after running the
maximum flow algorithm correspond to node disjoint paths between source and target in the original network.
This function handles both directed and undirected graphs, and can use all flow algorithms from NetworkX flow
package.
See also:
edge_disjoint_paths(), node_connectivity(), maximum_flow(), edmonds_karp(),
preflow_push(), shortest_augmenting_path()
[Link].average_node_connectivity
average_node_connectivity(G, flow_func=None)
Returns the average connectivity of a graph G.
The average connectivity bar{kappa} of a graph G is the average of local node connectivity over all pairs of
nodes of G1 .
∑︀
𝑢,𝑣 𝜅𝐺 (𝑢, 𝑣)
𝜅
¯ (𝐺) = (︀𝑛)︀
2
Parameters
• G (NetworkX graph) – Undirected graph
• flow_func (function) – A function for computing the maximum flow among a pair of
nodes. The function has to accept at least three parameters: a Digraph, a source node,
and a target node. And return a residual network that follows NetworkX conventions (see
maximum_flow() for details). If flow_func is None, the default maximum flow function
(edmonds_karp()) is used. See local_node_connectivity() for details. The
choice of the default function may change from version to version and should not be relied
on. Default value: None.
Returns K – Average node connectivity
Return type float
See also:
1 Beineke, L., O. Oellermann, and R. Pippert (2002). The average connectivity of a graph. Discrete mathematics 252(1-3), 31-45. http:
//[Link]/science/article/pii/S0012365X01001807
References
[Link].all_pairs_node_connectivity
[Link].edge_connectivity
• cutoff (integer, float) – If specified, the maximum flow algorithm will terminate when the
flow value reaches or exceeds the cutoff. This is only for the algorithms that support the cut-
off parameter: e.g., edmonds_karp() and shortest_augmenting_path(). Other
algorithms will ignore this parameter. Default value: None.
Returns K – Edge connectivity for G, or local edge connectivity if source and target were provided
Return type integer
Examples
You can use alternative flow algorithms for the underlying maximum flow computation. In dense net-
works the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp(), which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
If you specify a pair of nodes (source and target) as parameters, this function returns the value of local edge
connectivity.
>>> nx.edge_connectivity(G, 3, 7)
5
If you need to perform several local computations among different pairs of nodes on the same graph,
it is recommended that you reuse the data structures used in the maximum flow computations. See
local_edge_connectivity() for details.
Notes
This is a flow based implementation of global edge connectivity. For undirected graphs the algorithm works by
finding a ‘small’ dominating set of nodes of G (see algorithm 7 in1 ) and computing local maximum flow (see
local_edge_connectivity()) between an arbitrary node in the dominating set and the rest of nodes in
it. This is an implementation of algorithm 6 in1 . For directed graphs, the algorithm does n calls to the maximum
flow function. This is an implementation of algorithm 8 in1 .
See also:
local_edge_connectivity(), local_node_connectivity(), node_connectivity(),
maximum_flow(), edmonds_karp(), preflow_push(), shortest_augmenting_path(),
k_edge_components(), k_edge_subgraphs()
1 Abdol-Hossein Esfahanian. Connectivity Algorithms. [Link]
References
[Link].local_edge_connectivity
Examples
This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the
connectivity package:
We use in this example the platonic icosahedral graph, which has edge connectivity 5.
>>> G = nx.icosahedral_graph()
>>> local_edge_connectivity(G, 0, 6)
5
If you need to compute local connectivity on several pairs of nodes in the same graph, it is recommended that
you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for edge connectivity,
and the residual network for the underlying maximum flow computation.
Example of how to compute local edge connectivity among all pairs of nodes of the platonic icosahedral graph
reusing the data structures.
You can also use alternative flow algorithms for computing edge connectivity. For instance, in dense
networks the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp() which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
Notes
This is a flow based implementation of edge connectivity. We compute the maximum flow using, by default, the
edmonds_karp() algorithm on an auxiliary digraph build from the original input graph:
If the input graph is undirected, we replace each edge (u,`v`) with two reciprocal arcs (u, v) and (v, u) and
then we set the attribute ‘capacity’ for each arc to 1. If the input graph is directed we simply add the ‘capacity’
attribute. This is an implementation of algorithm 1 in1 .
The maximum flow in the auxiliary network is equal to the local edge connectivity because the value of a
maximum s-t-flow is equal to the capacity of a minimum s-t-cut (Ford and Fulkerson theorem).
See also:
edge_connectivity(), local_node_connectivity(), node_connectivity(),
maximum_flow(), edmonds_karp(), preflow_push(), shortest_augmenting_path()
References
[Link].local_node_connectivity
Examples
This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the
connectivity package:
We use in this example the platonic icosahedral graph, which has node connectivity 5.
>>> G = nx.icosahedral_graph()
>>> local_node_connectivity(G, 0, 6)
5
If you need to compute local connectivity on several pairs of nodes in the same graph, it is recommended that
you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for node connectivity,
and the residual network for the underlying maximum flow computation.
Example of how to compute local node connectivity among all pairs of nodes of the platonic icosahedral graph
reusing the data structures.
You can also use alternative flow algorithms for computing node connectivity. For instance, in dense
networks the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp() which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
Notes
This is a flow based implementation of node connectivity. We compute the maximum flow using, by default,
the edmonds_karp() algorithm (see: maximum_flow()) on an auxiliary digraph build from the original
input graph:
For an undirected graph G having n nodes and m edges we derive a directed graph H with 2n nodes and 2m+n
arcs by replacing each original node v with two nodes v_A, v_B linked by an (internal) arc in H. Then for each
edge (u, v) in G we add two arcs (u_B, v_A) and (v_B, u_A) in H. Finally we set the attribute capacity = 1 for
each arc in H1 .
For a directed graph G having n nodes and m arcs we derive a directed graph H with 2n nodes and m+n arcs by
replacing each original node v with two nodes v_A, v_B linked by an (internal) arc (v_A, v_B) in H. Then for
each arc (u, v) in G we add one arc (u_B, v_A) in H. Finally we set the attribute capacity = 1 for each arc in H.
This is equal to the local node connectivity because the value of a maximum s-t-flow is equal to the capacity of
a minimum s-t-cut.
1 Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and Erlebach, ‘Network Analysis: Methodological Foundations’,
Lecture Notes in Computer Science, Volume 3418, Springer-Verlag, 2005. [Link]
[Link]
See also:
local_edge_connectivity(), node_connectivity(), minimum_node_cut(),
maximum_flow(), edmonds_karp(), preflow_push(), shortest_augmenting_path()
References
[Link].node_connectivity
Examples
You can use alternative flow algorithms for the underlying maximum flow computation. In dense net-
works the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp(), which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
If you specify a pair of nodes (source and target) as parameters, this function returns the value of local node
connectivity.
>>> nx.node_connectivity(G, 3, 7)
5
If you need to perform several local computations among different pairs of nodes on the same graph,
it is recommended that you reuse the data structures used in the maximum flow computations. See
local_node_connectivity() for details.
Notes
This is a flow based implementation of node connectivity. The algorithm works by solving 𝑂((𝑛 − 𝛿 − 1 + 𝛿(𝛿 −
1)/2)) maximum flow problems on an auxiliary digraph. Where 𝛿 is the minimum degree of G. For details about
the auxiliary digraph and the computation of local node connectivity see local_node_connectivity().
This implementation is based on algorithm 11 in1 .
See also:
local_node_connectivity(), edge_connectivity(), maximum_flow(),
edmonds_karp(), preflow_push(), shortest_augmenting_path()
References
[Link].minimum_edge_cut
Returns cutset – Set of edges that, if removed, would disconnect G. If source and target nodes are
provided, the set contains the edges that if removed, would destroy all paths between source and
target.
Return type set
Examples
You can use alternative flow algorithms for the underlying maximum flow computation. In dense net-
works the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp(), which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
If you specify a pair of nodes (source and target) as parameters, this function returns the value of local edge
connectivity.
>>> nx.edge_connectivity(G, 3, 7)
5
If you need to perform several local computations among different pairs of nodes on the same graph,
it is recommended that you reuse the data structures used in the maximum flow computations. See
local_edge_connectivity() for details.
Notes
This is a flow based implementation of minimum edge cut. For undirected graphs the algorithm works by
finding a ‘small’ dominating set of nodes of G (see algorithm 7 in1 ) and computing the maximum flow between
an arbitrary node in the dominating set and the rest of nodes in it. This is an implementation of algorithm 6
in1 . For directed graphs, the algorithm does n calls to the max flow function. The function raises an error if the
directed graph is not weakly connected and returns an empty set if it is weakly connected. It is an implementation
of algorithm 8 in1 .
See also:
minimum_st_edge_cut(), minimum_node_cut(), stoer_wagner(),
node_connectivity(), edge_connectivity(), maximum_flow(), edmonds_karp(),
preflow_push(), shortest_augmenting_path()
1 Abdol-Hossein Esfahanian. Connectivity Algorithms. [Link]
References
[Link].minimum_node_cut
Examples
You can use alternative flow algorithms for the underlying maximum flow computation. In dense net-
works the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp(), which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
If you specify a pair of nodes (source and target) as parameters, this function returns a local st node cut.
If you need to perform several local st cuts among different pairs of nodes on the same graph, it is recommended
that you reuse the data structures used in the maximum flow computations. See minimum_st_node_cut()
for details.
Notes
This is a flow based implementation of minimum node cut. The algorithm is based in solving a number of
maximum flow computations to determine the capacity of the minimum cut on an auxiliary directed network that
corresponds to the minimum node cut of G. It handles both directed and undirected graphs. This implementation
is based on algorithm 11 in1 .
See also:
minimum_st_node_cut(), minimum_cut(), minimum_edge_cut(), stoer_wagner(),
node_connectivity(), edge_connectivity(), maximum_flow(), edmonds_karp(),
preflow_push(), shortest_augmenting_path()
References
[Link].minimum_st_edge_cut
Examples
This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the
connectivity package:
We use in this example the platonic icosahedral graph, which has edge connectivity 5.
>>> G = nx.icosahedral_graph()
>>> len(minimum_st_edge_cut(G, 0, 6))
5
If you need to compute local edge cuts on several pairs of nodes in the same graph, it is recommended that you
reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for edge connectivity,
and the residual network for the underlying maximum flow computation.
Example of how to compute local edge cuts among all pairs of nodes of the platonic icosahedral graph reusing
the data structures.
You can also use alternative flow algorithms for computing edge cuts. For instance, in dense networks the algo-
rithm shortest_augmenting_path() will usually perform better than the default edmonds_karp()
which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to
be explicitly imported from the flow package.
[Link].minimum_st_node_cut
Examples
This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the
connectivity package:
We use in this example the platonic icosahedral graph, which has node connectivity 5.
>>> G = nx.icosahedral_graph()
>>> len(minimum_st_node_cut(G, 0, 6))
5
If you need to compute local st cuts between several pairs of nodes in the same graph, it is recommended that
you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for node connectivity
and node cuts, and the residual network for the underlying maximum flow computation.
Example of how to compute local st node cuts reusing the data structures:
You can also use alternative flow algorithms for computing minimum st node cuts. For instance, in dense
networks the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp() which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
Notes
This is a flow based implementation of minimum node cut. The algorithm is based in solving a number of
maximum flow computations to determine the capacity of the minimum cut on an auxiliary directed network that
corresponds to the minimum node cut of G. It handles both directed and undirected graphs. This implementation
is based on algorithm 11 in1 .
See also:
minimum_node_cut(), minimum_edge_cut(), stoer_wagner(), node_connectivity(),
edge_connectivity(), maximum_flow(), edmonds_karp(), preflow_push(),
shortest_augmenting_path()
References
stoer_wagner(G[, weight, heap]) Returns the weighted minimum edge cut using the
Stoer-Wagner algorithm.
1 Abdol-Hossein Esfahanian. Connectivity Algorithms. [Link]
[Link].stoer_wagner