问题
I have cars,cities and routes. Every city is a node. Every route is a path generated by a car.
Different cars will have different path, sometimes paths could be intersected (which means differents cars have found the same city in they path), sometimes not.
I would rappresent a graph with all the cities and all the different path and plot the graph with plotly. Example:
List of cities: CityA -CityB -CityD -CityZ -CityK
List of cars: Car1, Car2
Routes:
Car1 will have a path through cityA - cityB - cityD this path will be colored in red
Car2 will have a path though cityZ - cityA - cityK this path will be colored in blue
Using networkx.classes.function.add_path I can't achive this because I will not preserve the information about different cars, there will be only the list of connected node:
As in the previous example add_path, G.edges(): [(CityA-CityB),(CityB-CityD),(CityZ-CityA),(CityA-CityK)]
I am not sure if what I am looking for could be achived with networkx.
A solution to plot is just passing the list to plotly but doing so I will not even use NetworkX and the next steps is to analize the graph.
回答1:
You can set node and edge attributes in NetworkX, which you can then use for instance to customize certain aspects of the plot. In this case, you could set a color attribute to the edges of the graph, and use this attribute to set the edge_color
in nx.draw. Here's how you could do this with the example paths you've shared:
import networkx as nx
from matplotlib import pyplot as plt
path_car1 = ['cityA','cityB','cityD']
path_car2 = ['cityZ','cityA','cityK']
paths = [path_car1, path_car2]
colors = ['Red','Blue']
Now create a directed graph, and iterate over the lists of paths, and assigned colors to add them as edges, an corresponding attributes:
G = nx.DiGraph()
for path, color in zip(paths, colors):
for edge in zip(path[:-1], path[1:]):
G.add_edge(*edge, color=color)
You can get the values of a given attribute for all edges with:
edge_colors = nx.get_edge_attributes(G, 'color')
Now when plotting you can set the edge colors through the edge_color
argument:
plt.figure(figsize=(10,7))
pos = nx.spring_layout(G, scale=20)
nx.draw(G, pos,
node_color='black',
with_labels=True,
node_size=1200,
edgelist=G.edges(),
edge_color=edge_colors.values(),
arrowsize=15,
font_color='white',
width=3,
alpha=0.9)
来源:https://stackoverflow.com/questions/61599058/assign-a-color-to-each-path-in-networkx