Article épinglé

dimanche 6 décembre 2020

Python, graphes et networkx

Quelques essais sous thonny

Essai de la bibliothèque networkx

Sources


Graphe simple

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

g = nx.Graph() # DiGraph() pour un graphe orienté
g.add_nodes_from(range(5))
g.add_edges_from([(0,1),(0,4),(0,3),(4,2),(1,3),(4,0),(1,2)])

print(g.degree())
print(g.number_of_nodes())
print(g.number_of_edges())

plt.figure()
nx.draw(g,with_labels=True)
plt.show()

>>>
[(0, 3), (1, 3), (2, 2), (3, 2), (4, 2)]
5
6

Graphe orienté

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

g = nx.DiGraph() # DiGraph() pour un graphe orienté
g.add_nodes_from(range(5))
g.add_edges_from([(0,1),(0,4),(0,3),(4,2),(1,3),(4,0),(1,2)])

print(g.degree())
print(g.number_of_nodes())
print(g.number_of_edges())

plt.figure()
nx.draw(g,with_labels=True)
plt.show()

>>>
[(0, 4), (1, 3), (2, 2), (3, 2), (4, 3)]
5
7


Deux graphes

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

g = nx.Graph() # DiGraph() pour un graphe orienté
g.add_nodes_from(range(5))
g.add_edges_from([(0,1),(0,4),(0,3),(4,2),(1,3),(4,0),(1,2)])

h=nx.Graph()
h.add_nodes_from(['a','b','c','d'])
h.add_edges_from([('a','b'),('b','c'),('c','d'),('d','a')])
print(g.degree())
print(g.number_of_nodes())
print(g.number_of_edges())


plt.figure()
nx.draw(g,with_labels=True,node_color="blue")
nx.draw(h,with_labels=True,node_color="red")
plt.show()



Graphe et voisin

Je découvre que les points et noeuds sont dans un dictionnaire

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

sommets=[1,2,3,4]

g = nx.Graph() # DiGraph() pour un graphe orienté
g.add_nodes_from(sommets)
g.add_edges_from([(1,4),(1,3),(1,2),(3,2),(4,2)])

print(g.number_of_nodes())
print(g.number_of_edges())
print(g.degree())


for i in g.nodes:
    voisin=nx.all_neighbors(g,i)
    print(i,len(list(voisin)))


print(type(voisin))

plt.figure()
nx.draw(g,with_labels=True,node_color="blue")
plt.show()


Video trajet pour snt





1 commentaire:

Enregistrer un commentaire

Tout commentaire nous engage ;)