1005 lines
No EOL
26 KiB
Text
1005 lines
No EOL
26 KiB
Text
{
|
||
"cells": [
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "c63fd7b0",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Tutorial\n",
|
||
"\n",
|
||
"This guide can help you start working with NetworkX.\n",
|
||
"\n",
|
||
"### Creating a graph\n",
|
||
"\n",
|
||
"Create an empty graph with no nodes and no edges."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "9dbf57b1",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"import networkx as nx\n",
|
||
"G = nx.Graph()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "f331cde1",
|
||
"metadata": {},
|
||
"source": [
|
||
"By definition, a `Graph` is a collection of nodes (vertices) along with\n",
|
||
"identified pairs of nodes (called edges, links, etc). In NetworkX, nodes can\n",
|
||
"be any [hashable](https://docs.python.org/3/glossary.html#term-hashable) object e.g., a text string, an image, an XML object,\n",
|
||
"another Graph, a customized node object, etc.\n",
|
||
"\n",
|
||
"# Nodes\n",
|
||
"\n",
|
||
"The graph `G` can be grown in several ways. NetworkX includes many\n",
|
||
"graph generator functions and\n",
|
||
"facilities to read and write graphs in many formats.\n",
|
||
"To get started though we’ll look at simple manipulations. You can add one node\n",
|
||
"at a time,"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "aa1473c2",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G.add_node(1)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d5a1a096",
|
||
"metadata": {},
|
||
"source": [
|
||
"or add nodes from any [iterable](https://docs.python.org/3/glossary.html#term-iterable) container, such as a list"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "1021bd00",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G.add_nodes_from([2, 3])"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2be42993",
|
||
"metadata": {},
|
||
"source": [
|
||
"You can also add nodes along with node\n",
|
||
"attributes if your container yields 2-tuples of the form\n",
|
||
"`(node, node_attribute_dict)`:\n",
|
||
"\n",
|
||
"```\n",
|
||
">>> G.add_nodes_from([\n",
|
||
"... (4, {\"color\": \"red\"}),\n",
|
||
"... (5, {\"color\": \"green\"}),\n",
|
||
"... ])\n",
|
||
"```\n",
|
||
"\n",
|
||
"Node attributes are discussed further below.\n",
|
||
"\n",
|
||
"Nodes from one graph can be incorporated into another:"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "5e648866",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"H = nx.path_graph(10)\n",
|
||
"G.add_nodes_from(H)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "c387d277",
|
||
"metadata": {},
|
||
"source": [
|
||
"`G` now contains the nodes of `H` as nodes of `G`.\n",
|
||
"In contrast, you could use the graph `H` as a node in `G`."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "880d2fe0",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G.add_node(H)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "196dcc1a",
|
||
"metadata": {},
|
||
"source": [
|
||
"The graph `G` now contains `H` as a node. This flexibility is very powerful as\n",
|
||
"it allows graphs of graphs, graphs of files, graphs of functions and much more.\n",
|
||
"It is worth thinking about how to structure your application so that the nodes\n",
|
||
"are useful entities. Of course you can always use a unique identifier in `G`\n",
|
||
"and have a separate dictionary keyed by identifier to the node information if\n",
|
||
"you prefer.\n",
|
||
"\n",
|
||
"# Edges\n",
|
||
"\n",
|
||
"`G` can also be grown by adding one edge at a time,"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "7f46c03b",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G.add_edge(1, 2)\n",
|
||
"e = (2, 3)\n",
|
||
"G.add_edge(*e) # unpack edge tuple*"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2aaa20e0",
|
||
"metadata": {},
|
||
"source": [
|
||
"by adding a list of edges,"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "1923234b",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G.add_edges_from([(1, 2), (1, 3)])"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "441aea9d",
|
||
"metadata": {},
|
||
"source": [
|
||
"or by adding any ebunch of edges. An *ebunch* is any iterable\n",
|
||
"container of edge-tuples. An edge-tuple can be a 2-tuple of nodes or a 3-tuple\n",
|
||
"with 2 nodes followed by an edge attribute dictionary, e.g.,\n",
|
||
"`(2, 3, {'weight': 3.1415})`. Edge attributes are discussed further\n",
|
||
"below."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "c8294a1c",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G.add_edges_from(H.edges)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "01e8ef66",
|
||
"metadata": {},
|
||
"source": [
|
||
"There are no complaints when adding existing nodes or edges. For example,\n",
|
||
"after removing all nodes and edges,"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "6c5069ec",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G.clear()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "96a9c6da",
|
||
"metadata": {},
|
||
"source": [
|
||
"we add new nodes/edges and NetworkX quietly ignores any that are\n",
|
||
"already present."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "83c04940",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G.add_edges_from([(1, 2), (1, 3)])\n",
|
||
"G.add_node(1)\n",
|
||
"G.add_edge(1, 2)\n",
|
||
"G.add_node(\"spam\") # adds node \"spam\"\n",
|
||
"G.add_nodes_from(\"spam\") # adds 4 nodes: 's', 'p', 'a', 'm'\n",
|
||
"G.add_edge(3, 'm')"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "361a6daf",
|
||
"metadata": {},
|
||
"source": [
|
||
"At this stage the graph `G` consists of 8 nodes and 3 edges, as can be seen by:"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "96829b46",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G.number_of_nodes()\n",
|
||
"G.number_of_edges()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "78d6d614",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"DG = nx.DiGraph()\n",
|
||
"DG.add_edge(2, 1) # adds the nodes in order 2, 1\n",
|
||
"DG.add_edge(1, 3)\n",
|
||
"DG.add_edge(2, 4)\n",
|
||
"DG.add_edge(1, 2)\n",
|
||
"assert list(DG.successors(2)) == [1, 4]\n",
|
||
"assert list(DG.edges) == [(2, 1), (2, 4), (1, 3), (1, 2)]"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2867c623",
|
||
"metadata": {},
|
||
"source": [
|
||
"# Examining elements of a graph\n",
|
||
"\n",
|
||
"We can examine the nodes and edges. Four basic graph properties facilitate\n",
|
||
"reporting: `G.nodes`, `G.edges`, `G.adj` and `G.degree`. These\n",
|
||
"are set-like views of the nodes, edges, neighbors (adjacencies), and degrees\n",
|
||
"of nodes in a graph. They offer a continually updated read-only view into\n",
|
||
"the graph structure. They are also dict-like in that you can look up node\n",
|
||
"and edge data attributes via the views and iterate with data attributes\n",
|
||
"using methods `.items()`, `.data()`.\n",
|
||
"If you want a specific container type instead of a view, you can specify one.\n",
|
||
"Here we use lists, though sets, dicts, tuples and other containers may be\n",
|
||
"better in other contexts."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "56a874f6",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"list(G.nodes)\n",
|
||
"list(G.edges)\n",
|
||
"list(G.adj[1]) # or list(G.neighbors(1))\n",
|
||
"G.degree[1] # the number of edges incident to 1"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "7f32bc91",
|
||
"metadata": {},
|
||
"source": [
|
||
"One can specify to report the edges and degree from a subset of all nodes\n",
|
||
"using an nbunch. An *nbunch* is any of: `None` (meaning all nodes),\n",
|
||
"a node, or an iterable container of nodes that is not itself a node in the\n",
|
||
"graph."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "fcbabf8c",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G.edges([2, 'm'])\n",
|
||
"G.degree([2, 3])"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "3b27a1ec",
|
||
"metadata": {},
|
||
"source": [
|
||
"# Removing elements from a graph\n",
|
||
"\n",
|
||
"One can remove nodes and edges from the graph in a similar fashion to adding.\n",
|
||
"Use methods\n",
|
||
"`Graph.remove_node()`,\n",
|
||
"`Graph.remove_nodes_from()`,\n",
|
||
"`Graph.remove_edge()`\n",
|
||
"and\n",
|
||
"`Graph.remove_edges_from()`, e.g."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "84b4eeb2",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G.remove_node(2)\n",
|
||
"G.remove_nodes_from(\"spam\")\n",
|
||
"list(G.nodes)\n",
|
||
"G.remove_edge(1, 3)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "8cd72dad",
|
||
"metadata": {},
|
||
"source": [
|
||
"# Using the graph constructors\n",
|
||
"\n",
|
||
"Graph objects do not have to be built up incrementally - data specifying\n",
|
||
"graph structure can be passed directly to the constructors of the various\n",
|
||
"graph classes.\n",
|
||
"When creating a graph structure by instantiating one of the graph\n",
|
||
"classes you can specify data in several formats."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "b7614d75",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G.add_edge(1, 2)\n",
|
||
"H = nx.DiGraph(G) # create a DiGraph using the connections from G\n",
|
||
"list(H.edges())\n",
|
||
"edgelist = [(0, 1), (1, 2), (2, 3)]\n",
|
||
"H = nx.Graph(edgelist) # create a graph from an edge list\n",
|
||
"list(H.edges())\n",
|
||
"adjacency_dict = {0: (1, 2), 1: (0, 2), 2: (0, 1)}\n",
|
||
"H = nx.Graph(adjacency_dict) # create a Graph dict mapping nodes to nbrs\n",
|
||
"list(H.edges())"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "5f8ef04d",
|
||
"metadata": {},
|
||
"source": [
|
||
"# What to use as nodes and edges\n",
|
||
"\n",
|
||
"You might notice that nodes and edges are not specified as NetworkX\n",
|
||
"objects. This leaves you free to use meaningful items as nodes and\n",
|
||
"edges. The most common choices are numbers or strings, but a node can\n",
|
||
"be any hashable object (except `None`), and an edge can be associated\n",
|
||
"with any object `x` using `G.add_edge(n1, n2, object=x)`.\n",
|
||
"\n",
|
||
"As an example, `n1` and `n2` could be protein objects from the RCSB Protein\n",
|
||
"Data Bank, and `x` could refer to an XML record of publications detailing\n",
|
||
"experimental observations of their interaction.\n",
|
||
"\n",
|
||
"We have found this power quite useful, but its abuse\n",
|
||
"can lead to surprising behavior unless one is familiar with Python.\n",
|
||
"If in doubt, consider using `convert_node_labels_to_integers()` to obtain\n",
|
||
"a more traditional graph with integer labels.\n",
|
||
"\n",
|
||
"# Accessing edges and neighbors\n",
|
||
"\n",
|
||
"In addition to the views `Graph.edges`, and `Graph.adj`,\n",
|
||
"access to edges and neighbors is possible using subscript notation."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "d340efb2",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G = nx.Graph([(1, 2, {\"color\": \"yellow\"})])\n",
|
||
"G[1] # same as G.adj[1]\n",
|
||
"G[1][2]\n",
|
||
"G.edges[1, 2]"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "03096d0e",
|
||
"metadata": {},
|
||
"source": [
|
||
"You can get/set the attributes of an edge using subscript notation\n",
|
||
"if the edge already exists."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "8ce00bdf",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G.add_edge(1, 3)\n",
|
||
"G[1][3]['color'] = \"blue\"\n",
|
||
"G.edges[1, 2]['color'] = \"red\"\n",
|
||
"G.edges[1, 2]"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "3981787f",
|
||
"metadata": {},
|
||
"source": [
|
||
"Fast examination of all (node, adjacency) pairs is achieved using\n",
|
||
"`G.adjacency()`, or `G.adj.items()`.\n",
|
||
"Note that for undirected graphs, adjacency iteration sees each edge twice."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "711e99a0",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"FG = nx.Graph()\n",
|
||
"FG.add_weighted_edges_from([(1, 2, 0.125), (1, 3, 0.75), (2, 4, 1.2), (3, 4, 0.375)])\n",
|
||
"for n, nbrs in FG.adj.items():\n",
|
||
" for nbr, eattr in nbrs.items():\n",
|
||
" wt = eattr['weight']\n",
|
||
" if wt < 0.5: print(f\"({n}, {nbr}, {wt:.3})\")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "10b59024",
|
||
"metadata": {},
|
||
"source": [
|
||
"Convenient access to all edges is achieved with the edges property."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "4d87898f",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"for (u, v, wt) in FG.edges.data('weight'):\n",
|
||
" if wt < 0.5:\n",
|
||
" print(f\"({u}, {v}, {wt:.3})\")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "fb80bff7",
|
||
"metadata": {},
|
||
"source": [
|
||
"# Adding attributes to graphs, nodes, and edges\n",
|
||
"\n",
|
||
"Attributes such as weights, labels, colors, or whatever Python object you like,\n",
|
||
"can be attached to graphs, nodes, or edges.\n",
|
||
"\n",
|
||
"Each graph, node, and edge can hold key/value attribute pairs in an associated\n",
|
||
"attribute dictionary (the keys must be hashable). By default these are empty,\n",
|
||
"but attributes can be added or changed using `add_edge`, `add_node` or direct\n",
|
||
"manipulation of the attribute dictionaries named `G.graph`, `G.nodes`, and\n",
|
||
"`G.edges` for a graph `G`.\n",
|
||
"\n",
|
||
"## Graph attributes\n",
|
||
"\n",
|
||
"Assign graph attributes when creating a new graph"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "eb49b8ed",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G = nx.Graph(day=\"Friday\")\n",
|
||
"G.graph"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "4507d4e2",
|
||
"metadata": {},
|
||
"source": [
|
||
"Or you can modify attributes later"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "9e580632",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G.graph['day'] = \"Monday\"\n",
|
||
"G.graph"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "8e6f3087",
|
||
"metadata": {},
|
||
"source": [
|
||
"# Node attributes\n",
|
||
"\n",
|
||
"Add node attributes using `add_node()`, `add_nodes_from()`, or `G.nodes`"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "04851bbc",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G.add_node(1, time='5pm')\n",
|
||
"G.add_nodes_from([3], time='2pm')\n",
|
||
"G.nodes[1]\n",
|
||
"G.nodes[1]['room'] = 714\n",
|
||
"G.nodes.data()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2f44f2be",
|
||
"metadata": {},
|
||
"source": [
|
||
"Note that adding a node to `G.nodes` does not add it to the graph, use\n",
|
||
"`G.add_node()` to add new nodes. Similarly for edges.\n",
|
||
"\n",
|
||
"# Edge Attributes\n",
|
||
"\n",
|
||
"Add/change edge attributes using `add_edge()`, `add_edges_from()`,\n",
|
||
"or subscript notation."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "3b4caf43",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G.add_edge(1, 2, weight=4.7 )\n",
|
||
"G.add_edges_from([(3, 4), (4, 5)], color='red')\n",
|
||
"G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})])\n",
|
||
"G[1][2]['weight'] = 4.7\n",
|
||
"G.edges[3, 4]['weight'] = 4.2"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "3129fd83",
|
||
"metadata": {},
|
||
"source": [
|
||
"The special attribute `weight` should be numeric as it is used by\n",
|
||
"algorithms requiring weighted edges.\n",
|
||
"\n",
|
||
" Directed graphs\n",
|
||
"\n",
|
||
"The `DiGraph` class provides additional methods and properties specific\n",
|
||
"to directed edges, e.g.,\n",
|
||
"`DiGraph.out_edges`, `DiGraph.in_degree`,\n",
|
||
"`DiGraph.predecessors`, `DiGraph.successors` etc.\n",
|
||
"To allow algorithms to work with both classes easily, the directed versions of\n",
|
||
"`neighbors` is equivalent to\n",
|
||
"`successors` while `degree` reports the sum\n",
|
||
"of `in_degree` and `out_degree` even though that may feel inconsistent at times."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "994396d5",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"DG = nx.DiGraph()\n",
|
||
"DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)])\n",
|
||
"DG.out_degree(1, weight='weight')\n",
|
||
"DG.degree(1, weight='weight')\n",
|
||
"list(DG.successors(1))\n",
|
||
"list(DG.neighbors(1))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "f1a2295b",
|
||
"metadata": {},
|
||
"source": [
|
||
"Some algorithms work only for directed graphs and others are not well\n",
|
||
"defined for directed graphs. Indeed the tendency to lump directed\n",
|
||
"and undirected graphs together is dangerous. If you want to treat\n",
|
||
"a directed graph as undirected for some measurement you should probably\n",
|
||
"convert it using `Graph.to_undirected()` or with"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "62477030",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"H = nx.Graph(G) # create an undirected graph H from a directed graph G"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "161d904c",
|
||
"metadata": {},
|
||
"source": [
|
||
"# Multigraphs\n",
|
||
"\n",
|
||
"NetworkX provides classes for graphs which allow multiple edges\n",
|
||
"between any pair of nodes. The `MultiGraph` and\n",
|
||
"`MultiDiGraph`\n",
|
||
"classes allow you to add the same edge twice, possibly with different\n",
|
||
"edge data. This can be powerful for some applications, but many\n",
|
||
"algorithms are not well defined on such graphs.\n",
|
||
"Where results are well defined,\n",
|
||
"e.g., `MultiGraph.degree()` we provide the function. Otherwise you\n",
|
||
"should convert to a standard graph in a way that makes the measurement\n",
|
||
"well defined."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "2952952f",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"MG = nx.MultiGraph()\n",
|
||
"MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)])\n",
|
||
"dict(MG.degree(weight='weight'))\n",
|
||
"GG = nx.Graph()\n",
|
||
"for n, nbrs in MG.adjacency():\n",
|
||
" for nbr, edict in nbrs.items():\n",
|
||
" minvalue = min([d['weight'] for d in edict.values()])\n",
|
||
" GG.add_edge(n, nbr, weight = minvalue)\n",
|
||
"\n",
|
||
"nx.shortest_path(GG, 1, 3)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "75473c78",
|
||
"metadata": {},
|
||
"source": [
|
||
"# Graph generators and graph operations\n",
|
||
"\n",
|
||
"In addition to constructing graphs node-by-node or edge-by-edge, they\n",
|
||
"can also be generated by\n",
|
||
"\n",
|
||
"## 1. Applying classic graph operations, such as:\n",
|
||
"\n",
|
||
"## 2. Using a call to one of the classic small graphs, e.g.,\n",
|
||
"\n",
|
||
"## 3. Using a (constructive) generator for a classic graph, e.g.,\n",
|
||
"\n",
|
||
"like so:"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "70f75060",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"K_5 = nx.complete_graph(5)\n",
|
||
"K_3_5 = nx.complete_bipartite_graph(3, 5)\n",
|
||
"barbell = nx.barbell_graph(10, 10)\n",
|
||
"lollipop = nx.lollipop_graph(10, 20)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "dc9d08fe",
|
||
"metadata": {},
|
||
"source": [
|
||
"# 4. Using a stochastic graph generator, e.g,\n",
|
||
"\n",
|
||
"like so:"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "c9e719fd",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"er = nx.erdos_renyi_graph(100, 0.15)\n",
|
||
"ws = nx.watts_strogatz_graph(30, 3, 0.1)\n",
|
||
"ba = nx.barabasi_albert_graph(100, 5)\n",
|
||
"red = nx.random_lobster(100, 0.9, 0.9)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "ab682ae0",
|
||
"metadata": {},
|
||
"source": [
|
||
"# 5. Reading a graph stored in a file using common graph formats\n",
|
||
"\n",
|
||
"NetworkX supports many popular formats, such as edge lists, adjacency lists,\n",
|
||
"GML, GraphML, LEDA and others."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "d020ea7d",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"nx.write_gml(red, \"path.to.file\")\n",
|
||
"mygraph = nx.read_gml(\"path.to.file\")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b79d9eba",
|
||
"metadata": {},
|
||
"source": [
|
||
"For details on graph formats see Reading and writing graphs\n",
|
||
"and for graph generator functions see Graph generators\n",
|
||
"\n",
|
||
" Analyzing graphs\n",
|
||
"\n",
|
||
"The structure of `G` can be analyzed using various graph-theoretic\n",
|
||
"functions such as:"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "0c40fb57",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G = nx.Graph()\n",
|
||
"G.add_edges_from([(1, 2), (1, 3)])\n",
|
||
"G.add_node(\"spam\") # adds node \"spam\"\n",
|
||
"list(nx.connected_components(G))\n",
|
||
"sorted(d for n, d in G.degree())\n",
|
||
"nx.clustering(G)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b45c5bd1",
|
||
"metadata": {},
|
||
"source": [
|
||
"Some functions with large output iterate over (node, value) 2-tuples.\n",
|
||
"These are easily stored in a [dict](https://docs.python.org/3/library/stdtypes.html#dict) structure if you desire."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "2a641901",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"sp = dict(nx.all_pairs_shortest_path(G))\n",
|
||
"sp[3]"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "1040d843",
|
||
"metadata": {},
|
||
"source": [
|
||
"See Algorithms for details on graph algorithms\n",
|
||
"supported.\n",
|
||
"\n",
|
||
"# Drawing graphs\n",
|
||
"\n",
|
||
"NetworkX is not primarily a graph drawing package but basic drawing with\n",
|
||
"Matplotlib as well as an interface to use the open source Graphviz software\n",
|
||
"package are included. These are part of the networkx.drawing\n",
|
||
"module and will be imported if possible.\n",
|
||
"\n",
|
||
"First import Matplotlib’s plot interface (pylab works too)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "55c5a07e",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"import matplotlib.pyplot as plt"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "18211e5d",
|
||
"metadata": {},
|
||
"source": [
|
||
"To test if the import of `nx_pylab` was successful draw `G`\n",
|
||
"using one of"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "adc5b19d",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G = nx.petersen_graph()\n",
|
||
"subax1 = plt.subplot(121)\n",
|
||
"nx.draw(G, with_labels=True, font_weight='bold')\n",
|
||
"subax2 = plt.subplot(122)\n",
|
||
"nx.draw_shell(G, nlist=[range(5, 10), range(5)], with_labels=True, font_weight='bold')"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "34185209",
|
||
"metadata": {},
|
||
"source": [
|
||
"when drawing to an interactive display. Note that you may need to issue a\n",
|
||
"Matplotlib"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "463bbac2",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "4665c907",
|
||
"metadata": {},
|
||
"source": [
|
||
"command if you are not using matplotlib in interactive mode."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "c77d0524",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"options = {\n",
|
||
" 'node_color': 'black',\n",
|
||
" 'node_size': 100,\n",
|
||
" 'width': 3,\n",
|
||
"}\n",
|
||
"subax1 = plt.subplot(221)\n",
|
||
"nx.draw_random(G, **options)\n",
|
||
"subax2 = plt.subplot(222)\n",
|
||
"nx.draw_circular(G, **options)\n",
|
||
"subax3 = plt.subplot(223)\n",
|
||
"nx.draw_spectral(G, **options)\n",
|
||
"subax4 = plt.subplot(224)\n",
|
||
"nx.draw_shell(G, nlist=[range(5,10), range(5)], **options)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e9074ec3",
|
||
"metadata": {},
|
||
"source": [
|
||
"You can find additional options via `draw_networkx()` and\n",
|
||
"layouts via the `layout module`.\n",
|
||
"You can use multiple shells with `draw_shell()`."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "d6acee87",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"G = nx.dodecahedral_graph()\n",
|
||
"shells = [[2, 3, 4, 5, 6], [8, 1, 0, 19, 18, 17, 16, 15, 14, 7], [9, 10, 11, 12, 13]]\n",
|
||
"nx.draw_shell(G, nlist=shells, **options)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "18276bc4",
|
||
"metadata": {},
|
||
"source": [
|
||
"To save drawings to a file, use, for example"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "065e299c",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"nx.draw(G)\n",
|
||
"plt.savefig(\"path.png\")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "857a0730",
|
||
"metadata": {},
|
||
"source": [
|
||
"This function writes to the file `path.png` in the local directory. If Graphviz and\n",
|
||
"PyGraphviz or pydot, are available on your system, you can also use\n",
|
||
"`networkx.drawing.nx_agraph.graphviz_layout` or\n",
|
||
"`networkx.drawing.nx_pydot.graphviz_layout` to get the node positions, or write\n",
|
||
"the graph in dot format for further processing."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "9f46b847",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"from networkx.drawing.nx_pydot import write_dot\n",
|
||
"pos = nx.nx_agraph.graphviz_layout(G)\n",
|
||
"nx.draw(G, pos=pos)\n",
|
||
"write_dot(G, 'file.dot')"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "94236c6e",
|
||
"metadata": {},
|
||
"source": [
|
||
"See Drawing for additional details.\n",
|
||
"\n",
|
||
"# NX-Guides\n",
|
||
"\n",
|
||
"If you are interested in learning more about NetworkX, graph theory and network analysis\n",
|
||
"then you should check out [nx-guides](https://networkx.org/nx-guides/index.html). There you can find tutorials,\n",
|
||
"real-world applications and in-depth examinations of graphs and network algorithms.\n",
|
||
"All the material is official and was developed and curated by the NetworkX community."
|
||
]
|
||
}
|
||
],
|
||
"metadata": {},
|
||
"nbformat": 4,
|
||
"nbformat_minor": 5
|
||
} |