logo

Graph (Network) Analysis Package NetworkX in Python 📂Graph Theory

Graph (Network) Analysis Package NetworkX in Python

Introduction

NetworkX is a Python package for analyzing graphs (networks).

Code

Installation

Enter the following in the terminal.

#설치
> pip install networkx

#버전 업데이트
> pip install --upgrade networkx

Importing and Checking Version

networkx is abbreviated as nx.

>>> import networkx as nx
>>> nx.__version__
'2.8.6'

Graph Creation

Create a null graph with the following code.

>>> G = nx.Graph()
>>> nx.info(G)
'Graph with 0 nodes and 0 edges'

Create a null directed graph with the following code.

>>> DG = nx.DiGraph()
>>> nx.info(DG)
'DiGraph with 0 nodes and 0 edges'

Adding and Removing Nodes

Use .add_node() to add a node. You can see the list of nodes in a graph with .nodes().

>>> G = nx.Graph()
>>> G.add_node("권은비")
>>> G.nodes()
NodeView(('권은비',))

You can add nodes with attributes. Using .nodes.data() will show the list of nodes with attributes.

>>> G.add_node("사쿠라", 회사="쏘스뮤직", 그룹="르세라핌")
>>> G.nodes()
NodeView(('권은비', '사쿠라'))
>>> G.nodes.data()
NodeDataView({'권은비': {}, '사쿠라': {'회사': '쏘스뮤직', '그룹': '르세라핌'}})

You can add multiple nodes at once using a list.

>>> G.add_nodes_from(["강혜원", "최예나", "이채연"])
>>> G.nodes()
NodeView(('권은비', '사쿠라', '강혜원', '최예나', '이채연'))

Nodes can be removed from the graph using .remove_node(), remove_nodes_from(), and edges connected to those nodes are also removed. .clear() removes all nodes and edges from the graph.

Adding and Removing Edges

Edges between two nodes can be added with .add_edge(), .add_edges_from().

>>> G.add_edge('사쿠라', '이채연')
>>> nx.info(G)
'Graph with 5 nodes and 1 edges'
>>> G.edges()
EdgeView([('사쿠라', '이채연')])

Adding an edge between non-existent nodes will also automatically add those nodes.

>>> G.add_edge('김채원', '조유리')
>>> G.add_edge('최예나', '조유리')
>>> G.add_edge('최예나', '김채원')
>>> G.nodes()
NodeView(('권은비', '사쿠라', '강혜원', '최예나', '이채연', '김채원', '조유리'))
>>> G.edges()
EdgeView([('사쿠라', '이채연'), ('최예나', '조유리'), ('최예나', '김채원'), ('김채원', '조유리')])

Specific edges can be removed from the graph using .remove_node(), remove_nodes_from(). .clear_edges() removes all edges from the graph.

Miscellaneous

Environment

  • OS: Windows11
  • Version: Python 3.9.2, networkx 2.8.6