Introduction to NetworkX Example
This is a post containing examples to add on to the previous post.
Modeling road network of India
Import the necessary packages
import networkx as nx
import matplotlib.pyplot as plt
import random
Create a graph object
G = nx.Graph()
city_list = ['Jaipur', 'Surat', 'Pune', 'Ahmedabad', 'Hyderabad',
'Bangalore', 'Chennai', 'Kolkata', 'New Delhi', 'Mumbai']
Create the nodes for each city in the graph
for each_city in city_list:
G.add_node(each_city)
nx.draw(G, with_labels=1)
plt.show()
Create a cost array to assign the costs to the edge
costs = list()
value = 100
# Assign total of 20 values
while(value <= 2000):
costs.append(value)
value += 100
Since there are 10 cities, add 20 edges to the graph in random
while(G.number_of_edges() <= 20):
# Choose one city at random from the set of cities
first_city = random.choice(list(G.nodes()))
# Choose second city
second_city = random.choice(list(G.nodes()))
# If the two cities are equal then discard
# If an edge already exists then discard
if first_city != second_city and not G.has_edge(first_city, second_city):
G.add_edge(first_city, second_city, weight = random.choice(costs))
nx.draw(G, with_labels = 1)
pos = nx.circular_layout(G)
nx.draw_networkx_edge_labels(G, pos)
plt.show()
Check if the graph is connected
print(nx.is_connected(G))
True