Graph types#

NetworkX provides data structures and methods for storing graphs.

All NetworkX graph classes allow (hashable) Python objects as nodes and any Python object can be assigned as an edge attribute.

The choice of graph class depends on the structure of the graph you want to represent.

Which graph class should I use?#

Networkx Class

Type

Self-loops allowed

Parallel edges allowed

Graph

undirected

Yes

No

DiGraph

directed

Yes

No

MultiGraph

undirected

Yes

Yes

MultiDiGraph

directed

Yes

Yes

Basic graph types#

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 may not necessarily be consistent across versions and platforms; however, the reporting for CPython is consistent across platforms and versions after 3.6.

Graph Views#

View of Graphs as SubGraph, Reverse, Directed, Undirected.

In some algorithms it is convenient to temporarily morph a graph to exclude some nodes or edges. It should be better to do that via a view than to remove and then re-add. In other algorithms it is convenient to temporarily morph a graph to reverse directed edges, or treat a directed graph as undirected, etc. This module provides those graph views.

The resulting views are essentially read-only graphs that report data from the original graph object. We provide an attribute G._graph which points to the underlying graph object.

Note: Since graphviews look like graphs, one can end up with view-of-view-of-view chains. Be careful with chains because they become very slow with about 15 nested views. For the common simple case of node induced subgraphs created from the graph class, we short-cut the chain by returning a subgraph of the original graph directly rather than a subgraph of a subgraph. We are careful not to disrupt any edge filter in the middle subgraph. In general, determining how to short-cut the chain is tricky and much harder with restricted_views than with induced subgraphs. Often it is easiest to use .copy() to avoid chains.

generic_graph_view(G[, create_using])

Returns a read-only view of G.

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

Core Views#

Views of core data structures such as nested Mappings (e.g. dict-of-dicts). These Views often restrict element access, with either the entire view or layers of nested mappings being read-only.

AtlasView(d)

An AtlasView is a Read-only Mapping of Mappings.

AdjacencyView(d)

An AdjacencyView is a Read-only Map of Maps of Maps.

MultiAdjacencyView(d)

An MultiAdjacencyView is a Read-only Map of Maps of Maps of Maps.

UnionAtlas(succ, pred)

A read-only union of two atlases (dict-of-dict).

UnionAdjacency(succ, pred)

A read-only union of dict Adjacencies as a Map of Maps of Maps.

UnionMultiInner(succ, pred)

A read-only union of two inner dicts of MultiAdjacencies.

UnionMultiAdjacency(succ, pred)

A read-only union of two dict MultiAdjacencies.

FilterAtlas(d, NODE_OK)

A read-only Mapping of Mappings with filtering criteria for nodes.

FilterAdjacency(d, NODE_OK, EDGE_OK)

A read-only Mapping of Mappings with filtering criteria for nodes and edges.

FilterMultiInner(d, NODE_OK, EDGE_OK)

A read-only Mapping of Mappings with filtering criteria for nodes and edges.

FilterMultiAdjacency(d, NODE_OK, EDGE_OK)

A read-only Mapping of Mappings with filtering criteria for nodes and edges.

Reporting Views#

NetworkX provides lightweight reporting views — read-only objects that report information about a graph without copying it. The most commonly used reporting views are:

  • NodeView — returned by G.nodes or G.nodes(...).

  • EdgeView — returned by G.edges or G.edges(...).

  • DegreeView — returned by G.degree or G.degree(...).

Quick overview#

Views are quick-to-create, live (they reflect changes to the graph), and provide Pythonic access patterns:

  • set-like membership and set operations for nodes and edges (n in G.nodes, G.nodes & H.nodes, (u, v) in G.edges),

  • iteration (for n in G.nodes, for u, v in G.edges),

  • mapping-style lookups (G.nodes[n] returns the node attribute dict; G.edges[u, v] returns the edge attribute dict),

  • data-filtered iteration via .data(...) and conversion to concrete containers via list(...) or dict(...).

Common usage patterns#

NodeView / NodeDataView

  • Use G.nodes when you need membership tests, set-like operations, or to look up a node’s attribute dict with G.nodes[n].

  • Use G.nodes(data=...) or G.nodes.data(attr_name, default=...) to iterate node/data pairs or to extract a single attribute for all nodes.

Example:

>>> G = nx.path_graph(3)
>>> list(G.nodes)
[0, 1, 2]
>>> G.add_node(3, color="red")
>>> list(G.nodes.data("color", default=None))
[(0, None), (1, None), (2, None), (3, 'red')]

EdgeView / EdgeDataView

  • Use G.edges to iterate or test membership for edges.

  • Call G.edges(data=...) or G.edges(nbunch=..., data=..., keys=...) to iterate edges with data, restrict to edges incident to a set of nodes, or include multigraph keys.

Note

Iteration of G.edges() yields node pairs as 2-tuples even for multigraphs. Use G.edges(keys=True) to receive 3-tuples (u, v, key) for multigraphs.

Example:

>>> G = nx.Graph()
>>> G.add_edge(0, 1, weight=3)
>>> list(G.edges(data="weight", default=1))
[(0, 1, 3)]

DegreeView

  • Use G.degree to iterate (node, degree) pairs or query a single node with G.degree[n].

  • The function interface G.degree(nbunch=..., weight=...) allows: * weight="attr" to compute weighted degree using the named edge attribute, and * nbunch to restrict iteration to a subset of nodes while still allowing direct lookups.

Example:

>>> G = nx.cycle_graph(4)
>>> dict(G.degree())
{0: 2, 1: 2, 2: 2, 3: 2}
>>> G.degree[0]
2
>>> # Add an edge with a weight attribute and compute weighted degrees:
>>> G.add_edge(0, 1, weight=5)
>>> dict(G.degree(weight="weight"))
{0: 6, 1: 6, 2: 2, 3: 2}

Note on how degree is computed#

NetworkX does not store a persistent degree value for each node. Instead, the degree is computed when requested by examining the neighbor dictionary for a node and counting or summing edge attributes as needed. For multigraphs the key dict for each neighbor is scanned; for weighted degree the requested edge attribute values are summed.

Because computing degree accesses the adjacency structures, some applications cache degree values in a separate dictionary to avoid repeated recomputation:

>>> G_degree = dict(G.degree)   # make a cached snapshot of degrees

If you cache degrees, remember to update the cached dict when you modify edges.

Performance & pitfalls#

  • Views are read-only wrappers — they do not copy graph data. If you need a stable snapshot (for example when you will modify the graph while iterating), materialize the view using list(view) or dict(view).

  • Avoid modifying the graph while iterating over a view (same rule as iterating a dict).

  • DataViews that return full attribute dicts expose writable dicts (modifying those dicts modifies the underlying graph attributes). Use this intentionally.

  • Edge set operations on undirected graphs use 2-tuple representations; be careful when comparing sets that may contain both (u, v) and (v, u).

  • DegreeView with weight performs a sum over edge attributes and can be more expensive than unweighted degree calculations.

Note#

This is a short summary for the Graph Types reference page. For the full implementation and detailed docstrings see networkx.classes.reportviews.

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.

Filter factories to hide or show sets of nodes and edges.

These filters return the function used when creating SubGraph.

no_filter(*items)

Returns a filter function that always evaluates to True.

hide_nodes(nodes)

Returns a filter function that hides specific nodes.

hide_edges(edges)

Returns a filter function that hides specific undirected edges.

hide_diedges(edges)

Returns a filter function that hides specific directed edges.

hide_multidiedges(edges)

Returns a filter function that hides specific multi-directed edges.

hide_multiedges(edges)

Returns a filter function that hides specific multi-undirected edges.

show_nodes(nodes)

Filter class to show specific nodes.

show_edges(edges)

Returns a filter function that shows specific undirected edges.

show_diedges(edges)

Returns a filter function that shows specific directed edges.

show_multidiedges(edges)

Returns a filter function that shows specific multi-directed edges.

show_multiedges(edges)

Returns a filter function that shows specific multi-undirected edges.