etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

NextworkX Python Overview

The Python NetworkX module contains tools for creating and manipulating, visualizing networks, also known as graphs. This is not only graph drawing package, but also collaborate with Matplotlib. By using this, we can implement highly flexible graph.

A graph is defined as a set of nodes and edges where each edge is associated with two nodes. NetworkX also adds the possibility to associate properties to each node and edge. The Networkx module is designed to handle data on a large scale relevant to modern problems. It has several classes for graphs and digraphs. It also has features to convert a graph from one to several formats.



Install Modules

The NetworkX can be installed using pip, Miniconda/Anaconda and from source code. Here, we have installed using pip tool -

pip install networkx

As this module is already installed in the system, that's why it returns the following -

Requirement already satisfied: networkx in c:\python37\scripts\projects\env\lib\site-packages (2.4)
Requirement already satisfied: decorator>=4.3.0 in c:\python37\scripts\projects\env\lib\site-packages (from networkx) (4.4.1)


Import NetworkX

First, we import the networkx module.

import networkx as nx


Create graph object

This module provides different classes for different networks, like directed and undirected networks. Let's create a basic undirected graph object -

g = nx.Graph() 




Adding or Removing Nodes

We can use add_node() method to add one graph node at a time or use add_nodes_from() method to add a list of nodes or a container of nodes.

# Add one node at a time
g.add_node(1)

# Add a list of nodes
g.add_nodes_from([2, 3, 4])

# container of nodes
cn = nx.path_graph(5)
g.add_nodes_from(cn)

To remove a node from the graph, simply use remove_node() method and pass the node.

g.remove_node(2)


Adding and Removing Edges

The add_edge() and add_edges_from() methods are used to add single and list of edges or container of edges respectively.

# Add single edge at a time
g.add_edge(1, 2)

# Add a list of edges
g.add_edges_from([(1,2), (1,3)])

To remove the edge from the graph, simply use remove_edge() method and pass the edge.

g.remove_edge(1,2)




Simple Example

import matplotlib.pyplot as plt 
import networkx as nx  
 
g = nx.Graph() 
  
fig = plt.figure(figsize =(5, 11))

g.add_edges_from([(1, 2), (1, 3), (1,4), (2, 3), (2, 4), (2, 5), (3, 4),  
                 (4, 5), (4, 6), (5, 7), (5, 8), (7, 8)]) 
  
# original Graph created 
plt.subplot(211) 
  
nx.draw(g)
plt.show()
plt.savefig('graph.png')

The above code returns the following output -

Networkx



Accessing Nodes and Edges

This module provides several methods to access the nodes and edges, number of nodes and edges and so on.

import matplotlib.pyplot as plt 
import networkx as nx  
 
g = nx.Graph() 
  
g.add_edges_from([(1, 2), (1, 3), (1,4), (2, 3), (2, 4), (2, 5), (3, 4),  
                 (4, 5), (4, 6), (5, 7), (5, 8), (7, 8)]) 
  
print(g.nodes())
print(g.edges())
print(g.degree(2))

print(g.number_of_nodes())
print(g.number_of_edges())


Convert to Directed Graph

The above generated graph is undirected graph, but we can also convert them to directed graph. To convert to directed graph, use to_directed() method. It returns the directed representation of graph.

import matplotlib.pyplot as plt 
import networkx as nx  
 
g = nx.Graph() 
  
fig = plt.figure(figsize =(5, 11))

g.add_edges_from([(1, 2), (1, 3), (1,4), (2, 3), (2, 4), (2, 5), (3, 4),  
                 (4, 5), (4, 6), (5, 7), (5, 8), (7, 8)]) 
  
# Directed Graph created 
plt.subplot(211) 
H = nx.to_directed(g)
nx.draw(H)
plt.show()
plt.savefig('graph.png')
Networkx Directed Graph

Similarly, we can convert a directed graph to undirected graph using to_undirected() method.





Related Articles

How to save figure in matplotlib pyplot
Python Line Plot Using Matplotlib
Matplotlib Pie Chart
Python Matplotlib Bar Plot
How to capture a video in Python OpenCV and save
Python OpenCV Overlaying or Blending Two Images
Contour Detection using Python OpenCV
Harris Corner Detection using Python OpenCV
Human Body Detection Program In Python OpenCV
Face Recognition OpenCV Source Code
Canny Edge Detector OpenCV Python
Python NumPy: Overview and Examples
Image processing using Python Pillow
Python OpenCV Histogram Equalization




Most Popular Development Resources
Characteristics of a Good Computer Program
-----------------
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP Create Word Document from HTML
-----------------
PHP code to send email using SMTP
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
How to get current directory, filename and code line number in PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
PHP MYSQL Advanced Search Feature
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Simple pagination in PHP with MySQL
-----------------
Fibonacci Series Program in PHP
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
How to add multiple custom markers on google map
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
Php file based authentication
-----------------
PHP Secure User Registration with Login/logout
-----------------
jQuery File upload progress bar with file size validation
-----------------
Polling system using PHP, Ajax and MySql
-----------------
Simple PHP File Cache
-----------------
SQL Injection Prevention Techniques
-----------------
Simple File Upload Script in PHP
-----------------
CSS Simple Menu Navigation Bar
-----------------
PHP User Authentication by IP Address
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
How to generate QR Code in PHP
-----------------
Calculate the distance between two locations using PHP
-----------------
Simple way to send SMTP mail using Node.js
-----------------
Detect Mobile Devices in PHP
-----------------
Set and Get Cookies in PHP
-----------------
To check whether a year is a leap year or not in php
-----------------
PHP Server Side Form Validation
-----------------
Date Timestamp Formats in PHP
-----------------
Get Visitor\'s location and TimeZone
-----------------
Simple Show Hide Menu Navigation
-----------------
Convert MySQL to JSON using PHP
-----------------
PHP Programming Error Types
-----------------
PHP Sending HTML form data to an Email
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
How to print specific part of a web page in javascript
-----------------
Google Street View API Example
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
PHP Getting Document of Remote Address
-----------------
PHP Connection and File Handling on FTP Server
-----------------
File Upload Validation in PHP
-----------------
R Plot Types
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial




General Knowledge

listen
listen
listen
listen
listen
listen
listen
listen
listen


Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 27

    Best AI Startups In India

    Artificial Intelligence is a process of making an intelligent computer machine that does tasks intelligently...

  • Jan 23

    Most in demand programming languages for 2019

    In this article, we have mentioned the analyzed results of the most in demand programming language for 2019...

  • Jan 15

    Web Robots

    Web robots is an internet robot or simply crawlers, or spiders and do not relate this with hardware robots...

  • Jan 12

    Most in demand NoSQL databases software for 2019

    In this article, we have mentioned the analyzed result of most in demand NoSQL database softwares for 2019...

  • Jan 10

    Kotlin : Android App Development Choice

    Kotlin is a general-purpose open-source programming language. It runs on the JVM and its syntax is much like Java...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2021. All Rights Reserved.