9.4 KiB
9.4 KiB
In [ ]:
import networkx as nx
import matplotlib.pyplot as plt
# Graphe orienté : une arête A -> B signifie "A suit B"
G = nx.DiGraph()
G.add_edges_from([
("Bob", "Alice"),
("David", "Alice"),
("Emma", "Alice"),
("Alice", "Chloé"), # Alice, très suivie, suit aussi Chloé
])
plt.figure()
pos = nx.spring_layout(G, seed=0)
nx.draw(G, pos, with_labels=True, node_color="lightblue", node_size=1200, arrows=True, arrowsize=20)
plt.show()In [ ]:
pr = nx.pagerank(G)
for personne, score in sorted(pr.items(), key=lambda x: -x[1]):
print(f"{personne} : {round(score, 3)}")
print("\nPour comparaison, degré entrant (nombre de personnes qui suivent) :")
for personne, deg in sorted(G.in_degree(), key=lambda x: -x[1]):
print(f"{personne} : {deg}")In [ ]:
from networkx.algorithms.community import asyn_lpa_communities
H = nx.Graph()
H.add_edges_from([
('Alice', 'Bob'), ('Alice', 'Emma'),
('Bob', 'Chloé'), ('Bob', 'Félix'),
('Chloé', 'David'), ('Chloé', 'Gaël')
])
communautes = list(asyn_lpa_communities(H, seed=3))
for i, communaute in enumerate(communautes):
print(f"Communauté {i+1} : {sorted(communaute)}")
# Visualisation avec une couleur par communauté détectée
palette = ["lightblue", "lightgreen", "lightcoral", "khaki"]
couleur_par_personne = {}
for i, communaute in enumerate(communautes):
for personne in communaute:
couleur_par_personne[personne] = palette[i]
plt.figure()
pos = nx.spring_layout(H, seed=0)
nx.draw(H, pos, with_labels=True, node_size=1200,
node_color=[couleur_par_personne[n] for n in H.nodes()])
plt.show()