NetworkX in Python
Here’s a useful sample code in $Python$ that uses the $NetworkX$ library to create, visualize, and analyze a graph.
This example covers basic graph operations, such as adding nodes and edges, visualizing the graph, and calculating common network metrics.
1. Installation
First, if you haven’t installed $NetworkX$, you can do so using:
1 | !pip install networkx |
2. Creating and Visualizing a Graph
Here’s a basic example of how to create a graph, add nodes and edges, visualize it, and calculate some metrics.
1 | import networkx as nx |
Explanation of the Code:
Graph Creation:
- We create a new undirected graph using
nx.Graph()
. - Nodes (“A”, “B”, “C”, “D”) are added individually.
- Edges are added between nodes to define the relationships.
- We create a new undirected graph using
Graph Visualization:
- The
nx.draw()
function is used to visualize the graph.
Nodes and edges are displayed with specified colors and sizes. plt.show()
displays the plot.
- The
Basic Graph Metrics:
- Nodes and Edges:
G.nodes()
andG.edges()
list all nodes and edges in the graph. - Degree: The degree of each node is calculated using
G.degree()
, which tells you how many connections each node has. - Shortest Path: The shortest path between two nodes is calculated using
nx.shortest_path()
. - Clustering Coefficient: The clustering coefficient measures the degree to which nodes in the graph tend to cluster together.
- Density: The density of a graph is calculated using
nx.density()
, which gives the ratio of the number of edges to the number of possible edges.
- Nodes and Edges:
Output
The graph is visualized with nodes labeled “A”, “B”, “C”, and “D”.
The console will display the nodes, edges, degree of each node, the shortest path from node “A” to node “D”, the clustering coefficient of each node, and the overall graph density.
3. Advanced Example: Directed Graph with Weighted Edges
Here’s an example with a directed graph, weighted edges, and calculation of PageRank.
1 | import networkx as nx |
Output:
Explanation:
- Directed Graph:
A directed graph is created usingnx.DiGraph()
. - Weighted Edges:
Edges are added with weights, which represent the strength or importance of the connection. - Visualization:
The directed graph is visualized with edge labels showing weights. - PageRank:
The PageRank algorithm is used to rank nodes, showing the importance of each node in the graph.
This should give you a good starting point for working with $NetworkX$ in Python.