4.8 KiB
4.8 KiB
In [ ]:
# %pip install networkx matplotlib
import networkx as nx
import matplotlib.pyplot as pltIn [ ]:
# Construisons un mini-réseau social
G = nx.Graph()
G.add_edges_from([
("Alice", "Bob"),
("Bob", "Claire"),
("Alice", "David"),
("Claire", "David"),
])
print("Nœuds :", list(G.nodes()))
print("Arêtes:", list(G.edges()))
plt.figure()
nx.draw(G, with_labels=True, node_color="lightblue", node_size=1000)
plt.show()In [ ]:
print("Nombre de sommets :", G.number_of_nodes())
print("Nombre d'arêtes :", G.number_of_edges())
print("Degrés de chaque sommet :", dict(G.degree()))
print("Degré moyen :", sum(dict(G.degree()).values())/G.number_of_nodes())In [ ]:
DG = nx.DiGraph()
DG.add_edges_from([
("Alice", "Bob"),
("Bob", "Claire"),
("Claire", "Alice")
])
plt.figure()
nx.draw(DG, with_labels=True, node_color="lightgreen", node_size=1000, arrows=True)
plt.show()
print("Degré sortant :", dict(DG.out_degree()))
print("Degré entrant :", dict(DG.in_degree()))In [ ]:
WG = nx.Graph()
WG.add_edge("Alice", "Bob", weight=5) # forte relation
WG.add_edge("Alice", "Claire", weight=1) # relation faible
print("Arêtes avec poids :", WG.edges(data=True))
# Dessin avec poids visibles
pos = nx.spring_layout(WG)
nx.draw(WG, pos, with_labels=True, node_color="lightcoral", node_size=1000)
labels = nx.get_edge_attributes(WG, "weight")
nx.draw_networkx_edge_labels(WG, pos, edge_labels=labels)
plt.show()