I am trying to create a railnet with different routes on a map. I am using Networkx and I am having trouble with providing different color for the routes(connections). Below, you can find the code that I have now.
The code now works in the sense that it does not give errors and provides a map with all the nodes and connections but it does not give different colors to the connections.
I also tried to draw the network edges in the loop but this did not work. I am very new to networkx and this is my first time using it.
Note: We are working as a group in github and the route.route is equal to a list of such form:
["Schiedam Centrum", "Delft", "Den Haag Centraal", "Gouda", "Rotterdam Alexander", "Rotterdam Centraal", "Dordrecht"]
Thanks in advance for having a look :)
def visualise(station_list, connections, network_object):
# Create a graph object
G = nx.Graph()
# Extract x, y coordinates, and station names
x = []
y = []
station_names = []
for station in station_list:
name, lon, lat = station.split(',')
if name in G.nodes:
continue
x.append(float(lat))
y.append(float(lon))
station_names.append(name)
# Add nodes to the graph
G.add_node(name, pos=(float(lat), float(lon)))
print(G.nodes)
# Create the map
plt.figure(figsize=(8, 20))
# Draw the stations as nodes
** pos = {name: (lon, lat) for name, lon, lat in zip(station_names, x, y)}
nx.draw_networkx_nodes(G, pos, node_color='yellow', node_size=100, edgecolors='black')
all_routes = network_object.routes
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w', '0.5', '0.75', '0.25', '0.1', '0.9', '0.3', '0.7', '0.2', '0.8', '0.4', '0.6', '0.0']
for route in all_routes:
for color in colors:
new_route = route.route
route_color = color
for a, b in zip(new_route, new_route[1:]):
G.add_edge(a.name, b.name)
for edge in G.edges:
if edge in new_route:
edge['color'] = route_color**
# Add labels to the stations
labels = {name: name for name in station_names}
nx.draw_networkx_labels(G, pos, labels, font_size=8)
# Draw the connections between stations as edges
nx.draw_networkx_edges(G, pos, width=2)
# Set map boundaries
plt.xlim(min(x) - 0.05, max(x) + 0.05)
plt.ylim(min(y) - 0.03, max(y) + 0.03)
# Add gridlines and title
plt.grid(True)
plt.title("Stations Map")
# Show the map
plt.show()
As said before I have tried to draw network edges in a loop. I am able to modify all edges in the draw edges, but then all will be the same color. I have not been able so far to modify edges individually.