Creating A Graph

import networkx as nx
 
G = nx.Graph() # Empty graph

Nodes

G.add_node(1) # add a single node
G.add_nodes_from([2, 3]) # add nodes from an iterable
G.add_nodes_from([(4, {"color": "red"}), (5, {"color": "green"})]) # add nodes with node attributes
 
# add nodes from another graph
H = nx.path_graph(10)
G.add_nodes_from(H)

Edges

G.add_edge(1, 2) # add a single edge
G.add_edges_from([(1, 2), (1, 3)]) # Add a list of edges
 
# add edges from another graph
H = nx.path_graph(10)
G.add_edges_from(H.edges)

Examining Elements

G.number_of_nodes()
G.number_of_edges()
 
list(G.nodes) # list of nodes
list(G.edges) # list of edges
 
# the adjacency objects (deges) of the node
G.adj[1]
G.neighbors(1)
 
# Set and get the edge attributes
G[1][2]['color'] = "blue"
G[1][2]
G.edges[1, 2]
 
# the degree of the node
G.degree[1]

Removing Elements

G.remove_node(2) # remove the node
G.remove_nodes_from([1, 2]) # removes the nodes and all adjacent edges.
 
G.remove_edge(1, 3) 
G.remove_edges_from([(1, 2), (2, 3)]) # remove the edges

Graph Constructors

H = nx.DiGraph(G) # create a directed-graph using another graph
 
edgelist = [(0, 1), (1, 2), (2, 3)]
H = nx.Graph(edgelist) # create a graph from an edge list
 
adjacency_dict = {0: (1, 2), 1: (0, 2), 2: (0, 1)}
H = nx.Graph(adjacency_dict)  # create a graph using adjacency dictionary

Attributes

# graph attributes
G = nx.Graph(day="Friday")
G.graph['day'] = "Monday"
 
# node attributes
G.add_node(1, time='5pm')
G.add_nodes_from([3], time='2pm')
G.nodes[1]['room'] = 714
# NodeDataView({1: {'time': '5pm', 'room': 714}, 3: {'time': '2pm'}})
 
# edge attributes
G.add_edge(1, 2, weight=4.7)
G.add_edges_from([(3, 4), (4, 5)], color='red')
G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})])
G[1][2]['weight'] = 4.7
G.edges[3, 4]['weight'] = 4.2

Directed Graphs

DG = nx.DiGraph()
DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)])
 
DG.out_degree(1, weight='weight')
# 0.5
DG.degree(1, weight='weight')
# 1.25
 
list(DG.successors(1))
# [2]
list(DG.neighbors(1))
# [2]
 
H = nx.Graph(G)  # create an undirected graph from a directed graph

Multigraphs

MG = nx.MultiGraph()
MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)])
dict(MG.degree(weight='weight'))
# {1: 1.25, 2: 1.75, 3: 0.5}

Drawing graphs

import matplotlib.pyplot as plt
 
_, ax = plt.subplots(1, 1, figsize=(8, 4))
 
G = nx.petersen_graph()
nx.draw(G, node_size=50, with_labels=True, ax=ax)
 
plt.show()

Drawing Layouts

nx.draw()
nx.draw_circular()
nx.draw_kamada_kawai()
nx.draw_planar()
nx.draw_random()
nx.draw_spectral()
nx.draw_spring()
nx.draw_shell()