How to?

networkx

Jan 15, 2024
langspython
1 Minutes
187 Words
This article was last updated on May 27, 2026 and some of the information may no longer be applicable due to the passage of time.

this package works together with matplotlib.

1
import networkx as nx
2
from matplotlib import pyplot as plt
3
4
g = nx.Graph()
5
6
g.add_node(1)
7
8
list(g.nodes())
9
10
g.add_nodes_from([3, 4])
11
12
print(g.nodes)
13
14
nx.draw(g)
15
nx.draw(g, with_labels=True)
51 collapsed lines
16
plt.show()
17
18
g.add_node('coin')
19
20
g.add_edge(1, 2)
21
e = (2, 3)
22
g.add_edge(*e)
23
24
g.add_edges_from([(1, 3), (1, 4), (1, 5)])
25
26
G.remove_node(2)
27
G.remove_nodes_from([4, 5, H, 'coin'])
28
print("les sommets de G sont : ", G.nodes)
29
30
edgelist = [(0, 1), (1, 2), (2, 3)]
31
I = nx.Graph(edgelist)
32
33
edgelist1 = [(0, 1), (0, 2), (0, 3)]
34
edgelist2 = [(0, 4), (0, 5), (0, 6)]
35
G1 = nx.Graph(edgelist1)
36
G2 = nx.Graph(edgelist2)
37
H1 = nx.disjoint_union(G1, G2) # make two graph in the same one
38
H2 = nx.compose(G1, G2) # make the same considering the node id
39
40
g = nx.petersen_graph() # a special graph
41
42
nx.draw_shell(g, nlist=[range(5, 10), range(5)]) # make 0, 1, 2, 3, 4 in a shell
43
44
options = {
45
'node_color': 'yellow',
46
'node_size': 500,
47
'width': 2,
48
'with_labels': True
49
}
50
51
nx.draw_random(G, **options)
52
plt.show()
53
54
nx.draw_circular(G, **options)
55
plt.show()
56
57
nx.draw_shell(G, nlist=[range(5, 10), range(5)], **options)
58
plt.show()
59
60
nx.draw(G)
61
plt.savefig("graph.png")
62
63
G2= nx.DiGraph ()
64
G2.add_edges_from([(0, 1),(1,0), (0, 2), (0, 3)])
65
nx.draw_random(G2, with_labels=True, font_weight='bold')
66
plt.show()

draw in particular position

1
G=nx.Graph()
2
G.add_edges_from([[1,2],[2,3],[3,1]])
3
position={1:[0,2],2:[2,0],3:[0,0]} #dictionnaire où on précise les coordonnées de chacun des sommets
4
nx.draw(G,pos=position)
Article title:networkx
Article author:Julyfun
Release time:Jan 15, 2024
Copyright 2026
Sitemap