Make graphs in Python with NetworkX

Jérémie Decock (www.jdhp.org)

Attention:

Veuillez noter que ce document est en cours de rédaction. Dans son état actuel, il n'est pas destiné à être lu par d'autres personnes que ses auteurs.

In [1]:
%matplotlib inline

import networkx as nx
import matplotlib.pyplot as plt

Example 1

In [2]:
g = nx.Graph()

g.add_node("Foo")
g.add_edge("Foo", 1)
g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(1, 4)
g.add_edge(3, 4)
In [3]:
list(g.nodes())
Out[3]:
[1, 2, 3, 'Foo', 4]
In [5]:
pos = nx.spring_layout(g)

nx.draw_networkx(g, pos, node_color='#ffaaff', node_size=800)

Example 2

In [6]:
g = nx.Graph()
g.add_edges_from([(0, 1), (0, 2), (0, 3), (1, 2)])
In [7]:
list(g.nodes())
Out[7]:
[0, 1, 2, 3]
In [9]:
pos = nx.spring_layout(g)

nx.draw_networkx_nodes(g, pos, node_size=20)
nx.draw_networkx_edges(g, pos, alpha=0.4)
Out[9]:
<matplotlib.collections.LineCollection at 0x11a19c940>

Random graph

In [10]:
g = nx.gnm_random_graph(10, 20)
In [11]:
list(g.nodes())
Out[11]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [13]:
pos = nx.spring_layout(g)

nx.draw_networkx_nodes(g, pos, node_size=20)
nx.draw_networkx_edges(g, pos, alpha=0.4)
nx.draw_networkx_labels(g, pos, alpha=0.4);