{"id":18292,"date":"2021-06-20T19:54:28","date_gmt":"2021-06-20T19:54:28","guid":{"rendered":"https:\/\/www.askpython.com\/?p=18292"},"modified":"2021-06-22T16:26:19","modified_gmt":"2021-06-22T16:26:19","slug":"networkx-package","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/networkx-package","title":{"rendered":"NetworkX Package &#8211; Python Graph Library"},"content":{"rendered":"\n<p>The NetworkX Package is a Python library for studying graphs and networks. It provides tools for the creation, manipulation, and study of dynamic and complex network structures. With NetworkX, we can load and store networks in many data formats, generate many types of random and classic networks, analyze network structure, build network models, design new network algorithms, draw networks, and much more. In this tutorial, we will learn how to use NetworkX to create graphs and study networks.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Importing the NetworkX Package<\/h2>\n\n\n\n<p>In order to use the NetworkX package, we need to download it on our local machine. You can download it using the <a href=\"https:\/\/www.askpython.com\/python-modules\/python-pip\" data-type=\"post\" data-id=\"3848\">pip command<\/a>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\npip install networkx\n<\/pre><\/div>\n\n\n<p>And then you can import the library as follows.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport networkx as nx\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Adding nodes to the graph<\/h2>\n\n\n\n<p>First, we will create an empty graph by calling <code>Graph()<\/code> class as shown below.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nG = nx.Graph()\n<\/pre><\/div>\n\n\n<p>A node in NetworkX can be any <a href=\"https:\/\/docs.python.org\/3\/glossary.html#term-hashable\" target=\"_blank\" rel=\"noreferrer noopener\">hashable<\/a> object, i.e., an integer, a text string, an image, an XML object, etc. It can be a NetworkX graph also. There are 2 methods used to add nodes in graph.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><em><strong>add_node():<\/strong><\/em> This method is used to add 1 single node at a time.<\/li><li><em><strong>add_nodes_from():<\/strong><\/em> This method takes an iterable container such as list, set, etc and add multiple nodes at the same time.<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport networkx as nx\n\nG = nx.Graph()\n\nG.add_node(1)\nG.add_nodes_from(&#x5B;2,3,&quot;node 5&quot;])\nprint(G.nodes())\n<\/pre><\/div>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n&#x5B;1, 2, 3, &#039;node 5&#039;]\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Adding edges to the graph<\/h2>\n\n\n\n<p>An edge is a link between 2 nodes. These 2 methods are majorly used to add edges to the graph. Unknown nodes specified in the parameters are automatically added to the graph.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong><em>add_edge():<\/em><\/strong> This method adds one edge at a time. <\/li><li><em><strong>add_edges_from():<\/strong><\/em> This method takes an iterable container of edges tuples like list, iterator, etc.<\/li><\/ul>\n\n\n\n<p>Adding a node or an edge again to the graph will be silently ignored by NetworkX.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport networkx as nx\n\nG = nx.Graph()\n\n# Adding one edge at a time\n# Node 1 and 2 will be automatically added\nG.add_edge(1,2)\nG.add_edge(3,2)\n\n# Adding multiple edges at a time\nG.add_edges_from(&#x5B;(4,2), (3,5), (5,4)])\n\n# Adding duplicates will be ignored.\nG.add_node(1)\nG.add_edge(1,2)\n\nprint(G.nodes())\nprint(G.edges())\n<\/pre><\/div>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n&#x5B;1, 2, 3, 4, 5]\n&#x5B;(1, 2), (2, 3), (2, 4), (3, 5), (4, 5)]\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Removing Nodes and Edges from the graph<\/h2>\n\n\n\n<p>Similarly to adding nodes and edges, we can remove single nodes and edges at a time and multiple nodes and edges as well at a time.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong><em>remove_node():<\/em><\/strong> This method removes one node and edges associated with that node from the graph. If the node doesn&#8217;t exist in the graph, it will raise <code>NetworkXError<\/code>.<\/li><li><strong><em>remove_nodes_from():<\/em><\/strong> This method takes an iterable container and removes all nodes and edges associated with those nodes from the graph. If any node doesn&#8217;t exist in the graph, it will silently discard it without any changes.<\/li><li><strong><em>remove_edge():<\/em><\/strong> This method removes one edge from the graph keeping the nodes as it is. If the edge doesn&#8217;t exist in the graph, it will raise <code>NetworkXError<\/code>.<\/li><li><strong><em>remove_edges_from():<\/em><\/strong> This method takes an iterable container and removes edges from the graph. If any edge doesn&#8217;t exist in the graph, it will silently discard it without any changes.<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport networkx as nx\n\nG = nx.Graph()\n\n# Creating graph\nG.add_edges_from(&#x5B;(1, 2), (2, 3), (3, 4), (4, 1)])\nG.add_edges_from(&#x5B;(5, 6), (5, 7), (5, 8), (7, 8)])\n\nprint(G.nodes())\nprint(G.edges())\n\n# Removing edge 1-2 from graph\nG.remove_edge(2, 1)\n# Removing edge 3-4 and 1-4 at once\nG.remove_edges_from(&#x5B;(3, 4), (1, 4)])\n\nprint()\nprint(G.nodes())\nprint(G.edges())\n\n# Removing node 5 from graph\nG.remove_node(5)\n# Removing node 7 and 8\nG.remove_nodes_from(&#x5B;7,8])\n\nprint()\nprint(G.nodes())\nprint(G.edges())\n<\/pre><\/div>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n&#x5B;1, 2, 3, 4, 5, 6, 7, 8]\n&#x5B;(1, 2), (1, 4), (2, 3), (3, 4), (5, 6), (5, 7), (5, 8), (7, 8)]\n\n&#x5B;1, 2, 3, 4, 5, 6, 7, 8]\n&#x5B;(2, 3), (5, 6), (5, 7), (5, 8), (7, 8)]\n\n&#x5B;1, 2, 3, 4, 6]\n&#x5B;(2, 3)]\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Accessing elements of graph<\/h2>\n\n\n\n<p>We can access 4 basic graph properties in NetworkX graph.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong><em>G.nodes:<\/em><\/strong> It returns the list of nodes in the graph.<\/li><li><strong><em>G.edges:<\/em><\/strong> It returns the list of edges in the graph.<\/li><li><strong><em>G.adj:<\/em><\/strong> It returns the adjacency list for all the nodes. An adjacency list of node X contains neighboring nodes that are directly linked to node X. You can access all the neighboring nodes of a node using a subscript notation(using square brackets after <code>G.adj<\/code>).<\/li><li><strong><em>G.degree:<\/em><\/strong> It returns the number of nodes linked to each node in the graph. You can access the degree of a node using a subscript notation(using square brackets after <code>G.degree<\/code>).<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport networkx as nx\n\nG = nx.Graph()\n\nG.add_edges_from(&#x5B;(1,2), (1,3), (3,4), (3,5)])\n\nprint(&quot;Nodes&quot;)\nprint(G.nodes)\nprint(&quot;Edges&quot;)\nprint(G.edges)\nprint(&quot;Adjacency List&quot;)\nprint(G.adj)\nprint(&quot;Degree&quot;)\nprint(G.degree)\n\nprint()\n\nprint(&quot;Adjacency List for node 3&quot;)\nprint(G.adj&#x5B;3])\nprint(&quot;Degree for node 3&quot;)\nprint(G.degree&#x5B;3])\n<\/pre><\/div>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nNodes\n&#x5B;1, 2, 3, 4, 5]\nEdges\n&#x5B;(1, 2), (1, 3), (3, 4), (3, 5)]\nAdjacency List\n{1: {2: {}, 3: {}}, 2: {1: {}}, 3: {1: {}, 4: {}, 5: {}}, 4: {3: {}}, 5: {3: {}}}\nDegree\n&#x5B;(1, 2), (2, 1), (3, 3), (4, 1), (5, 1)]\n\nAdjacency List for node 3\n{1: {}, 4: {}, 5: {}}\nDegree for node 3\n3\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Attributes for Graph, Nodes, and Edges<\/h2>\n\n\n\n<p>Each graph, node, and edge can hold key\/value attribute pairs in an associated attribute dictionary. By default these are empty, but attributes can be added or changed using&nbsp;<code>add_edge<\/code>,&nbsp;<code>add_node<\/code>&nbsp;or direct manipulation of the attribute dictionaries named&nbsp;<code>G.graph<\/code>,&nbsp;<code>G.nodes<\/code>, and&nbsp;<code>G.edges<\/code>&nbsp;for a graph&nbsp;<code>G<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. Graph Attributes<\/h3>\n\n\n\n<p>You can assign attributes to graph while creating it using <code>nx.Graph()<\/code>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport networkx as nx\nG = nx.Graph(graph_description = &quot;This is an empty graph&quot;)\nprint(G.graph)\n# Output: {&#039;graph_description&#039;: &#039;This is an empty graph&#039;}\n<\/pre><\/div>\n\n\n<p>Or you can add\/modify the attributes later just like a dictionary object<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport networkx as nx\nG = nx.Graph()\nG.graph&#x5B;&quot;description&quot;] = &quot;This is empty graph&quot; \nG.graph&#x5B;&quot;data&quot;] = 5\nprint(G.graph)\n# Output: {&#039;description&#039;: &#039;This is empty graph&#039;, &#039;data&#039;: 5}\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">2. Node Attributes<\/h3>\n\n\n\n<p>You can add attributes for nodes using <code>add_node()<\/code>, <code>add_nodes_from()<\/code> or <code>G.nodes<\/code>. You can get attributes for all nodes using <code>G.nodes.data()<\/code>. For a particular node use square brackets as shown.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport networkx as nx\nG = nx.Graph()\n\n# Using add_node\nG.add_node(1, data = &quot;data1&quot;)\n\n# Using add_nodes_from\nG.add_nodes_from(&#x5B;(2, {&quot;data&quot;: &quot;data2&quot;}),\n                  (3, {&quot;data&quot;: &quot;data3&quot;})], \n                   node_type = &quot;child node&quot;)\n\n# Adding more attributes on node 1 using G.nodes\nG.nodes&#x5B;1]&#x5B;&quot;type&quot;] = &quot;root node&quot;\n\nprint(G.nodes.data())\n# Output: &#x5B;(1, {&#039;data&#039;: &#039;data1&#039;, &#039;type&#039;: &#039;root node&#039;}), (2, {&#039;node_type&#039;: &#039;child node&#039;, &#039;data&#039;: &#039;data2&#039;}), (3, {&#039;node_type&#039;: &#039;child node&#039;, &#039;data&#039;: &#039;data3&#039;})]\n\nprint(G.nodes&#x5B;1])\n# Output: {&#039;data&#039;: &#039;data1&#039;, &#039;type&#039;: &#039;root node&#039;}\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">3. Edge Attributes &#8211; Making a weighted graph<\/h3>\n\n\n\n<p>You can add attributes for edges using <code>add_edge()<\/code>, <code>add_edges_from()<\/code>, <code>G.edges<\/code> or subscript notation. By assigning attributes to edges, we can create a weighted graph as shown.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport networkx as nx\nG = nx.Graph()\n\n# Using add_edge\nG.add_edge(1, 2, weight = 50)\n\n# Using add_edges_from\nG.add_edges_from(&#x5B;\n                  (1, 3, {&quot;weight&quot;: 70}),\n                  (1, 4, {&quot;weight&quot;: 100})\n                ])\n\n# Using subscript notation\nG.add_edge(4,5)\nG&#x5B;4]&#x5B;5]&#x5B;&quot;weight&quot;] = 175\n\n# Using G.edges\nG.edges&#x5B;1, 2]&#x5B;&quot;weight&quot;] = 10\n\nprint(G.edges.data())\n\n# Output: &#x5B;(1, 2, {&#039;weight&#039;: 10}), (1, 3, {&#039;weight&#039;: 70}), (1, 4, {&#039;weight&#039;: 100}), (4, 5, {&#039;weight&#039;: 175})]\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Visualizing NetworkX Package Graphs<\/h2>\n\n\n\n<p>We can draw graphs and visualize them in the NetworkX package using the <code>draw()<\/code> method as shown.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport networkx as nx\n\nG = nx.Graph()\n\n# Using add_edge\nG.add_edge(1, 2, weight = 12.5)\nG.add_edge(3, 2, weight = 50.0)\nG.add_edge(1, 3, weight = 17)\nG.add_edge(4, 2, weight = 100)\nG.add_edge(2, 5, weight = 1)\nG.add_edge(4, 6, weight = 25.5)\nG.add_edge(7, 4, weight = 175)\nG.add_edge(5, 8, weight = 90)\n\nnx.draw(G, with_labels= True, font_weight=&#039;bold&#039;)\n<\/pre><\/div>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"446\" height=\"302\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/06\/NetworkX-Graph-Visualization.png\" alt=\"NetworkX Graph Visualization\" class=\"wp-image-18319\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/06\/NetworkX-Graph-Visualization.png 446w, https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/06\/NetworkX-Graph-Visualization-300x203.png 300w\" sizes=\"auto, (max-width: 446px) 100vw, 446px\" \/><figcaption>NetworkX Graph Visualization<\/figcaption><\/figure><\/div>\n\n\n\n<p>If you want to draw graphs with weights use <code>draw_networkx_edge_labels()<\/code> along with <code>nx.draw()<\/code> specifying the graph, pos and edge_label attributes<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nG = nx.Graph()\n\n# Using add_edge\nG.add_edge(1, 2, weight = 12.5)\nG.add_edge(3, 2, weight = 50.0)\nG.add_edge(1, 3, weight = 17)\nG.add_edge(4, 2, weight = 100)\nG.add_edge(2, 5, weight = 1)\nG.add_edge(4, 6, weight = 25.5)\nG.add_edge(7, 4, weight = 175)\nG.add_edge(5, 8, weight = 90)\n\n\npos=nx.circular_layout(G)\nnx.draw(G, pos, with_labels=True, font_weight=&#039;bold&#039;)\nedge_weight = nx.get_edge_attributes(G,&#039;weight&#039;)\nnx.draw_networkx_edge_labels(G, pos, edge_labels = edge_weight)\nplt.show()\n<\/pre><\/div>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"446\" height=\"302\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/06\/NetworkX-Graph-Visualization-With-Weights.png\" alt=\"NetworkX Graph Visualization With Weights\" class=\"wp-image-18321\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/06\/NetworkX-Graph-Visualization-With-Weights.png 446w, https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/06\/NetworkX-Graph-Visualization-With-Weights-300x203.png 300w\" sizes=\"auto, (max-width: 446px) 100vw, 446px\" \/><figcaption>NetworkX Graph Visualization With Weights<\/figcaption><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Creating Directed Graphs using the NetworkX Package<\/h2>\n\n\n\n<p>NetworkX also allows you to create directed graphs using <code>DiGraph()<\/code> class which provides additional methods and properties specific to directed edges, e.g.,&nbsp;<code>DiGraph.out_edges<\/code>,&nbsp;<code>DiGraph.in_degree<\/code>,&nbsp;<code>DiGraph.predecessors()<\/code>,&nbsp;<code>DiGraph.successors()<\/code>&nbsp;etc.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport networkx as nx\n\nDG = nx.DiGraph()\n\nDG.add_edges_from(&#x5B;(1,2), (2,3), (3,4), (4,5), (5,2), (4, 6)])\n\n# Print edges going out from node 4\nprint(&quot;Out edges of node 4 are:&quot;,DG.out_edges(4))\n\n# Print in degree of node 2\nprint(&quot;In Degree of node 2 is:&quot;,DG.in_degree(2))\n\n# Print successors of node 4\nprint(&quot;Successors of node 4 are:&quot;,list(DG.successors(4)))\n\n# Print predecessors of node 2\nprint(&quot;Predecessors of node 2 are:&quot;,list(DG.predecessors(2)))\n\nnx.draw(DG, with_labels= True, font_weight=&#039;bold&#039;)\n<\/pre><\/div>\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nOut edges of node 4 are: &#x5B;(4, 5), (4, 6)]\nIn Degree of node 2 is: 2\nSuccessors of node 4 are: &#x5B;5, 6]\nPredecessors of node 2 are: &#x5B;1, 5]\n<\/pre><\/div>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"446\" height=\"302\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/06\/NetwokX-Directed-Graph.png\" alt=\"NetwokX Directed Graph\" class=\"wp-image-18327\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/06\/NetwokX-Directed-Graph.png 446w, https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/06\/NetwokX-Directed-Graph-300x203.png 300w\" sizes=\"auto, (max-width: 446px) 100vw, 446px\" \/><figcaption>NetworkX Directed Graph<\/figcaption><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this tutorial, you learned about NetworkX package and how to use it to create, manipulate and visualize graphs. This library becomes helpful in studying complex networks and graphs. It is used by mathematicians, physicists, biologists, computer scientists, etc for study.<\/p>\n\n\n\n<p>Thanks for reading!!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The NetworkX Package is a Python library for studying graphs and networks. It provides tools for the creation, manipulation, and study of dynamic and complex network structures. With NetworkX, we can load and store networks in many data formats, generate many types of random and classic networks, analyze network structure, build network models, design new [&hellip;]<\/p>\n","protected":false},"author":31,"featured_media":18325,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-18292","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-modules"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/18292","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/31"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=18292"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/18292\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/18325"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=18292"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=18292"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=18292"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}