Python package for creating and manipulating graphs and networks
npx @tessl/cli install tessl/pypi-networkx@2.8.0A comprehensive Python library for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks and graphs. NetworkX provides extensive algorithms for graph analysis including shortest paths, centrality measures, clustering, connectivity analysis, and community detection.
pip install networkximport networkx as nxCommon for specific functionality:
from networkx import Graph, DiGraph, MultiGraph, MultiDiGraph
from networkx.algorithms import shortest_path, betweenness_centrality
from networkx.generators import complete_graph, random_graphimport networkx as nx
import matplotlib.pyplot as plt
# Create a simple graph
G = nx.Graph()
# Add nodes
G.add_node(1)
G.add_nodes_from([2, 3, 4])
# Add edges
G.add_edge(1, 2)
G.add_edges_from([(2, 3), (3, 4), (4, 1)])
# Basic graph properties
print(f"Number of nodes: {G.number_of_nodes()}")
print(f"Number of edges: {G.number_of_edges()}")
print(f"Nodes: {list(G.nodes())}")
print(f"Edges: {list(G.edges())}")
# Compute shortest path
path = nx.shortest_path(G, source=1, target=3)
print(f"Shortest path from 1 to 3: {path}")
# Compute centrality
centrality = nx.betweenness_centrality(G)
print(f"Betweenness centrality: {centrality}")
# Draw the graph
nx.draw(G, with_labels=True, node_color='lightblue',
node_size=500, font_size=16, font_weight='bold')
plt.show()NetworkX provides a flexible graph data structure and extensive algorithm library:
The library is designed for maximum reusability across network analysis applications, research projects, and educational purposes.
Core graph data structures supporting different types of networks: undirected graphs, directed graphs, and multigraphs with flexible node and edge attribute storage.
class Graph:
def __init__(self, incoming_graph_data=None, **attr): ...
def add_node(self, node_for_adding, **attr): ...
def add_edge(self, u_of_edge, v_of_edge, **attr): ...
def number_of_nodes(self): ...
def number_of_edges(self): ...
class DiGraph(Graph):
def in_degree(self, nbunch=None, weight=None): ...
def out_degree(self, nbunch=None, weight=None): ...
def predecessors(self, n): ...
def successors(self, n): ...Extensive collection of graph algorithms including shortest paths, centrality measures, connectivity analysis, community detection, and more. Over 100+ algorithms covering all major areas of graph theory.
def shortest_path(G, source=None, target=None, weight=None, method='dijkstra'): ...
def betweenness_centrality(G, k=None, normalized=True, weight=None, endpoints=False, seed=None): ...
def connected_components(G): ...
def pagerank(G, alpha=0.85, personalization=None, max_iter=100, tol=1e-06, nstart=None, weight='weight', dangling=None): ...Functions to create various types of graphs including classic graphs, random graphs, social networks, lattices, trees, and specialized network structures.
def complete_graph(n, create_using=None): ...
def path_graph(n, create_using=None): ...
def cycle_graph(n, create_using=None): ...
def random_graph(n, p, seed=None, directed=False): ...
def barabasi_albert_graph(n, m, seed=None, initial_graph=None): ...Functions to convert between NetworkX graphs and other data structures including matrices, pandas DataFrames, dictionaries, and edge lists.
def to_networkx_graph(data, create_using=None, multigraph_input=False): ...
def to_numpy_array(G, nodelist=None, dtype=None, order=None, multigraph_weight=sum, weight='weight', nonedge=0.0): ...
def from_pandas_adjacency(df, create_using=None): ...
def to_dict_of_dicts(G, nodelist=None, edge_data=None): ...Reading and writing graphs in various formats including adjacency lists, edge lists, GraphML, GML, GEXF, Pajek, and custom formats.
def read_edgelist(path, comments='#', delimiter=None, create_using=None, nodetype=None, data=True, edgetype=None, encoding='utf-8'): ...
def write_edgelist(G, path, comments='#', delimiter=' ', data=True, encoding='utf-8'): ...
def read_graphml(path, node_type=str, edge_key_type=str, encoding='utf-8'): ...
def write_gml(G, path, stringizer=None): ...Graph layout algorithms and drawing functions with matplotlib integration for visualizing networks.
def draw(G, pos=None, ax=None, **kwds): ...
def spring_layout(G, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, weight='weight', scale=1, center=None, dim=2, seed=None): ...
def circular_layout(G, scale=1, center=None, dim=2): ...
def kamada_kawai_layout(G, dist=None, pos=None, weight='weight', scale=1, center=None, dim=2): ...Essential utility functions for graph manipulation, analysis, and operations. These functions provide fundamental graph operations and property checking capabilities.
def density(G): ...
def degree_histogram(G): ...
def freeze(G): ...
def is_frozen(G): ...
def info(G, n=None): ...
def create_empty_copy(G, with_data=True): ...
def set_node_attributes(G, values, name=None): ...
def get_node_attributes(G, name): ...
def set_edge_attributes(G, values, name=None): ...
def get_edge_attributes(G, name): ...
def is_weighted(G): ...
def is_empty(G): ...
def nodes_with_selfloops(G): ...
def number_of_selfloops(G): ...Graph matrix operations and spectral analysis including adjacency matrices, Laplacian matrices, and eigenvalue computations.
def adjacency_matrix(G, nodelist=None, dtype=None, weight='weight'): ...
def laplacian_matrix(G, nodelist=None, weight='weight'): ...
def adjacency_spectrum(G, weight='weight'): ...
def algebraic_connectivity(G, weight='weight', normalized=True, tol=1e-8, method='tracemin_pcg', seed=None): ...# Node types
NodeType = Any # Any hashable Python object except None
# Graph attribute types
NodeAttr = Dict[str, Any]
EdgeAttr = Dict[str, Any]
GraphAttr = Dict[str, Any]
# Data structure types
NodeView = Mapping[NodeType, NodeAttr]
EdgeView = Mapping[Tuple[NodeType, NodeType], EdgeAttr]
DegreeView = Mapping[NodeType, int]
# Common return types
PathType = List[NodeType]
ComponentType = Set[NodeType]
CentralityDict = Dict[NodeType, float]