networkx 2.8.2 Pypi GitHub Homepage
Other Docs
ParametersBackRef

A DiGraph stores nodes and edges with optional data, or attributes.

DiGraphs hold directed edges. Self loops are allowed but multiple (parallel) edges are not.

Nodes can be arbitrary (hashable) Python objects with optional key/value attributes. By convention :None:None:`None` is not used as a node.

Edges are represented as links between nodes with optional key/value 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 any format that is supported by the to_networkx_graph() function, currently including edge list, dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy sparse matrix, or PyGraphviz graph.

attr : keyword arguments, optional (default= no attributes)

Attributes to add to graph as key=value pairs.

Base class for directed graphs.

See Also

Graph
MultiDiGraph
MultiGraph
OrderedDiGraph

Examples

Create an empty graph structure (a "null graph") with no nodes and no edges.

>>> G = nx.DiGraph()

G can be grown in several ways.

Nodes:

Add one node at a time:

>>> 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).

>>> G.add_nodes_from([2, 3])
... G.add_nodes_from(range(100, 110))
... H = nx.path_graph(10)
... G.add_nodes_from(H)

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,

>>> G.add_edges_from([(1, 2), (1, 3)])

or a collection of edges,

>>> G.add_edges_from(H.edges)

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 = nx.DiGraph(day="Friday")
... G.graph {'day': 'Friday'}

Add node attributes using add_node(), add_nodes_from() or G.nodes

>>> G.add_node(1, time="5pm")
... G.add_nodes_from([3], time="2pm")
... G.nodes[1] {'time': '5pm'}
>>> G.nodes[1]["room"] = 714
... del G.nodes[1]["room"] # remove attribute
... list(G.nodes(data=True)) [(1, {'time': '5pm'}), (3, {'time': '2pm'})]

Add edge attributes using add_edge(), add_edges_from(), subscript notation, or G.edges.

>>> G.add_edge(1, 2, weight=4.7)
... G.add_edges_from([(3, 4), (4, 5)], color="red")
... G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
... G[1][2]["weight"] = 4.7
... G.edges[1, 2]["weight"] = 4

Warning: we protect the graph data structure by making :None:None:`G.edges[1, 2]` a read-only dict-like structure. However, you can assign to attributes in e.g. :None:None:`G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change data attributes: :None:None:`G.edges[1, 2]['weight'] = 4` (For multigraphs: :None:None:`MG.edges[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 :None:None:`G.adj` or :None:None:`G.adjacency()`

>>> for n, nbrsdict in G.adjacency():
...  for nbr, eattr in nbrsdict.items():
...  if "weight" in eattr:
...  # Do something useful with the edges
...  pass

But the edges reporting object is often more convenient:

>>> for u, v, weight in G.edges(data="weight"):
...  if weight is not None:
...  # Do something useful with the edges
...  pass

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 similarly to dict-views. The objects nodes , edges and :None:None:`adj` provide access to data attributes via lookup (e.g. :None:None:`nodes[n]`, :None:None:`edges[u, v]`, :None:None:`adj[u][v]`) and iteration (e.g. :None:None:`nodes.items()`, :None:None:`nodes.data('color')`, :None:None:`nodes.data('color', default='blue')` and similarly for edges ) Views exist for nodes , edges , :None:None:`neighbors()`/:None:None:`adj` and degree .

For details on these and other miscellaneous methods, see below.

Subclasses (Advanced):

The Graph class uses a dict-of-dict-of-dict data structure. The outer dict (node_dict) holds adjacency information keyed by node. The next dict (adjlist_dict) represents the adjacency information and holds edge data keyed by neighbor. The inner dict (edge_attr_dict) represents the edge data and holds edge attribute values keyed by attribute names.

Each of these three dicts can be replaced in a subclass 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_attr_dict_factory and graph_attr_dict_factory.

node_dict_factory

node_dict_factory

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

adjlist_outer_dict_factory

adjlist_inner_dict_factory

adjlist_inner_dict_factory

edge_attr_dict_factory

edge_attr_dict_factory

graph_attr_dict_factory

graph_attr_dict_factory

Typically, if your extension doesn't impact the data structure all methods will inherited without issue except: :None:None:`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

to_directed_class

to_undirected_class

to_undirected_class

Subclassing Example

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.

>>> class ThinGraph(nx.Graph):
...  all_edge_dict = {"weight": 1} ... ... def single_edge_dict(self): ... return self.all_edge_dict ... ... edge_attr_dict_factory = single_edge_dict
>>> G = ThinGraph()
... G.add_edge(2, 1)
... G[2][1] {'weight': 1}
>>> G.add_edge(2, 2)
... G[2][1] is G[2][2] True

Please see ~networkx.classes.ordered for more examples of creating graph subclasses by overwriting the base class :None:None:`dict` with a dictionary-like object.

See :

Back References

The following pages refer to to this document either explicitly or contain code examples using this.

networkx

123 Elements
networkx.algorithms.dag.descendants
networkx.algorithms.cycles.find_cycle
networkx.algorithms.flow.mincost.min_cost_flow
networkx.algorithms.components.weakly_connected.weakly_connected_components
networkx.algorithms.shortest_paths.unweighted.single_target_shortest_path
networkx.algorithms.centrality.reaching.local_reaching_centrality
networkx.readwrite.adjlist.read_adjlist
networkx.algorithms.isomorphism.isomorphvf2.DiGraphMatcher.__init__
networkx.algorithms.components.strongly_connected.is_strongly_connected
networkx.classes.graph.Graph
networkx.algorithms.centrality.reaching.global_reaching_centrality
networkx.algorithms.flow.preflowpush.preflow_push
networkx.algorithms.tree.branchings.branching_weight
networkx.algorithms.tournament.hamiltonian_path
networkx.algorithms.dag.all_topological_sorts
networkx.readwrite.json_graph.tree.tree_data
networkx.classes.digraph.DiGraph.to_undirected
networkx.algorithms.flow.networksimplex.network_simplex
networkx.algorithms.components.semiconnected.is_semiconnected
networkx.classes.multidigraph.MultiDiGraph
networkx.algorithms.flow.mincost.min_cost_flow_cost
networkx.readwrite.multiline_adjlist.read_multiline_adjlist
networkx.algorithms.assortativity.neighbor_degree.average_neighbor_degree
networkx.classes.multigraph.MultiGraph
networkx.algorithms.cycles.simple_cycles
networkx.algorithms.connectivity.disjoint_paths.edge_disjoint_paths
networkx.algorithms.connectivity.cuts.minimum_st_node_cut
networkx.generators.classic.complete_graph
networkx.classes.digraph.DiGraph
networkx.algorithms.traversal.edgedfs.edge_dfs
networkx.algorithms.shortest_paths.weighted.goldberg_radzik
networkx.algorithms.components.strongly_connected.kosaraju_strongly_connected_components
networkx.algorithms.operators.unary.reverse
networkx.classes.graph.Graph.to_undirected
networkx.algorithms.traversal.breadth_first_search.descendants_at_distance
networkx.algorithms.traversal.depth_first_search.dfs_tree
networkx.algorithms.dag.topological_generations
networkx.algorithms.components.weakly_connected.number_weakly_connected_components
networkx.linalg.modularitymatrix.directed_modularity_matrix
networkx.algorithms.shortest_paths.weighted.bellman_ford_predecessor_and_distance
networkx.algorithms.isomorphism.temporalisomorphvf2.TimeRespectingDiGraphMatcher.__init__
networkx.drawing.nx_pylab.draw_networkx_edges
networkx.algorithms.distance_regular.is_distance_regular
networkx.algorithms.connectivity.disjoint_paths.node_disjoint_paths
networkx.algorithms.components.strongly_connected.number_strongly_connected_components
networkx.readwrite.edgelist.read_edgelist
networkx.algorithms.link_analysis.pagerank_alg.pagerank
networkx.classes.multidigraph.MultiDiGraph.to_undirected
networkx.algorithms.dag.dag_longest_path
networkx.algorithms.flow.maxflow.minimum_cut
networkx.algorithms.approximation.traveling_salesman.threshold_accepting_tsp
networkx.generators.lattice.grid_graph
networkx.algorithms.moral.moral_graph
networkx.algorithms.connectivity.edge_augmentation.complement_edges
networkx.algorithms.assortativity.pairs.node_degree_xy
networkx.generators.trees.random_tree
networkx.algorithms.shortest_paths.weighted.negative_edge_cycle
networkx.classes.function.is_negatively_weighted
networkx.algorithms.flow.dinitz_alg.dinitz
networkx.algorithms.flow.mincost.max_flow_min_cost
networkx.algorithms.flow.maxflow.minimum_cut_value
networkx.algorithms.tree.recognition.is_branching
networkx.algorithms.components.weakly_connected.is_weakly_connected
networkx.algorithms.assortativity.pairs.node_attribute_xy
networkx.algorithms.dominance.dominance_frontiers
networkx.drawing.nx_pydot.from_pydot
networkx.algorithms.tree.recognition.is_arborescence
networkx.algorithms.shortest_paths.weighted.dijkstra_predecessor_and_distance
networkx.readwrite.json_graph.node_link.node_link_graph
networkx.algorithms.components.strongly_connected.strongly_connected_components
networkx.readwrite.pajek.read_pajek
networkx.algorithms.traversal.edgebfs.edge_bfs
networkx.algorithms.dag.antichains
networkx.readwrite.json_graph.tree.tree_graph
networkx.algorithms.flow.boykovkolmogorov.boykov_kolmogorov
networkx.algorithms.traversal.breadth_first_search.bfs_successors
networkx.algorithms.components.strongly_connected.strongly_connected_components_recursive
networkx.generators.directed.gnr_graph
networkx.readwrite.text.forest_str
networkx.algorithms.shortest_paths.dense.floyd_warshall_predecessor_and_distance
networkx.algorithms.centrality.voterank_alg.voterank
networkx.readwrite.json_graph.node_link.node_link_data
networkx.generators.directed.gn_graph
networkx.algorithms.flow.edmondskarp.edmonds_karp
networkx.algorithms.connectivity.connectivity.local_node_connectivity
networkx.algorithms.approximation.traveling_salesman.asadpour_atsp
networkx.algorithms.tournament.is_strongly_connected
networkx.readwrite.gml.read_gml
networkx.algorithms.isomorphism.isomorph.is_isomorphic
networkx.algorithms.euler.is_eulerian
networkx.algorithms.connectivity.cuts.minimum_st_edge_cut
networkx.algorithms.connectivity.connectivity.local_edge_connectivity
networkx.algorithms.link_analysis.pagerank_alg.pagerank_numpy
networkx.generators.joint_degree_seq.directed_joint_degree_graph
networkx.algorithms.dominance.immediate_dominators
networkx.algorithms.shortest_paths.unweighted.single_target_shortest_path_length
networkx.algorithms.flow.maxflow.maximum_flow
networkx.algorithms.dag.ancestors
networkx.algorithms.shortest_paths.weighted.johnson
networkx.algorithms.shortest_paths.astar.astar_path
networkx.readwrite.json_graph.cytoscape.cytoscape_graph
networkx.algorithms.flow.maxflow.maximum_flow_value
networkx.readwrite.json_graph.adjacency.adjacency_graph
networkx.generators.degree_seq.directed_configuration_model
networkx.algorithms.traversal.breadth_first_search.bfs_predecessors
networkx.algorithms.link_analysis.pagerank_alg.pagerank_scipy
networkx.algorithms.tournament.score_sequence
networkx.algorithms.approximation.traveling_salesman.greedy_tsp
networkx.classes.graph.Graph.number_of_edges
networkx.algorithms.tournament.is_reachable
networkx.algorithms.tournament.is_tournament
networkx.algorithms.dag.lexicographical_topological_sort
networkx.classes.graph.Graph.to_directed
networkx.algorithms.flow.shortestaugmentingpath.shortest_augmenting_path
networkx.classes.graphviews.reverse_view
networkx.algorithms.shortest_paths.weighted.find_negative_cycle
networkx.algorithms.dag.dag_longest_path_length
networkx.algorithms.approximation.traveling_salesman.simulated_annealing_tsp
networkx.algorithms.dag.transitive_reduction
networkx.algorithms.dag.transitive_closure_dag
networkx.algorithms.dag.topological_sort
networkx.classes.function.is_weighted
networkx.algorithms.flow.capacityscaling.capacity_scaling

Local connectivity graph

Hover to see nodes names; edges to Self not shown, Caped at 50 nodes.

Using a canvas is more power efficient and can get hundred of nodes ; but does not allow hyperlinks; , arrows or text (beyond on hover)

SVG is more flexible but power hungry; and does not scale well to 50 + nodes.

All aboves nodes referred to, (or are referred from) current nodes; Edges from Self to other have been omitted (or all nodes would be connected to the central node "self" which is not useful). Nodes are colored by the library they belong to, and scaled with the number of references pointing them


GitHub : /networkx/classes/digraph.py#21
type: <class 'type'>
Commit: