Introduction to NetworkX
NetworkX is a Python package for modeling, analyzing, and visializing networks
- several types of networks
- several algorithms for network analysis
- read/write networks in many formats
At first, we must import the module networkx
Creating Simple Graphs
The graph can have an arbitrary additional information.
Nodes in graphs manipulated with networkx can be arbitrary objects that are hashable. Most commnon are numbers and strings.
nx.add_nodes_from(X) can be any iterable container.
Even a graph can be a node!
The argument E in nx.add_nodes_from(E) can be any iterable container of edge-tuples. An edge-tuple can be
- a 2-tuple -
- a 3-tuple -
, dc), where
dcis a dictionary of edge attributes.
- Adding existing nodes is no error.
- Adding existing edges is no error.
- Even a graph can be a node!
- Any edge and node can have an arbitrary number of atributes.
Removing Nodes and Edges
Accessing Nodes and Edges
Atributes of Graphs, Nodes and Edges
Each grah, node and edge can have attributes that are stored in a associated attribute dictionary. Attributes are empty by default.
They can be added when creating a new graph
changed or added later
Warning: Adding nodes to
G.nodes does not add them to the graph. It is necessary to use
add_nodes_from(). Similarly for edges!
Edge Attributes (cont)
weight is special, as it is used by several algorithms implemented in
networkx. Therefore the attribute
weight must be numeric.
Oops! What is the error?
Once again with the
Directed graph are represented by the class
DiGraph with some specific properties, like
DiGraph.successors(). Actually, the directed versions of
neighbors() is equivalent to
degree reports the sum of
1. Construct a Simple Graph
gener_house_graph() that returns an undirected graph representing the following drawing
Implement the following functions, assume that graph is undirected if not said otherwise:
A center of a graph is a node where the maximum distance (number of edges) traversed to any other node is a minimum, compared to any other node. Essentially, the center of a graph is the most centrally located node. Note that there may be more than one node that qualifies as the center of the graph.