import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
Exercise 01
Complex Networks INPE 2025
- read an adjacency matrix from a file
- calculate the number of nodes and edges
- promote different graph’s visualizations
- think about different metrics on the graph
1. Matrix load
Adjacency matrix creation based on numpy
methods:
123)
np.random.seed(
= np.random.randint(0, 2, size=(10, 10))
A = np.triu(A, 1)
A = A + A.T A
Now the graph can be created, based on matrix A
:
= nx.from_numpy_array(A) G
2. Nodes and edges
Counting nodes and edges:
print(f'Nodes: {len(G.nodes)}')
print(f'Edges: {len(G.edges)}')
Nodes: 10
Edges: 17
3. Visualization
Using matplotlib
and nx.draw
:
=(8, 5), dpi=300)
plt.figure(figsize
nx.draw(
G,=True,
with_labels='lightblue',
node_color='grey',
edge_color=1000,
node_size=10,
font_size
)
plt.show()
4. Metrics
4.1 Global metrics
Average shortest path length:
print(nx.average_shortest_path_length(G))
1.7777777777777777
4.2 Node metrics
Betweenness:
= nx.betweenness_centrality(G)
betweenness =(8, 5), dpi=300)
plt.figure(figsize= nx.spring_layout(G, seed=42)
pos = nx.draw_networkx_nodes(
nodes
G,
pos,=list(betweenness.values()),
node_color=1000
node_size
)= nx.draw_networkx_edges(G, pos, alpha=0.4)
edges = nx.draw_networkx_labels(G, pos, font_size=10)
labels ="Betweenness Centrality") plt.colorbar(nodes, label