Set a different color for a path

心已入冬 提交于 2021-02-10 20:28:27

问题


I have a weighted graph,G, extracted from a text file:

i   j   distance
1   2   6000 
1   3   4000
2   1   6000
2   6   5000
....

And I have specific a route (not a shortest path) that I want to plot on graph G, i.e. [1, 2, 6, 7] that starts from node 1, end at node 7 by visiting node 2 and node 6. Here the code I've tried. But since Im new in python and networkx package as well, I couldn't get the result that Im looking for.

G = nx.read_edgelist('Graph.txt', data=(('weight',float),))
r=[1,2,6,7]
edges=[]
route_edges=[(r[n], r[n+1]) for n in range (len(r)-1)]
G.add_nodes_from(r)
G.add_edges_from(route_edges)
edges.append(route_edges)
pos=nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos=pos)
nx.draw_networkx_labels(G, pos=pos)
nx.draw_networkx_edges(G,pos=pos,edgelist=edges)

I want to plot whole edges and the path that I defined with different colors and also I want to add different color to node 6.


回答1:


To highlight a specific path in a different color, it's just a matter of setting a different color edge color for the path edges. For you can define a set containing the list's pairs of nodes as tuples, and set a color or another to the graphs' edges depending on whether the path is contained in the set:

#graph defined with from_pandas_edgelist for simplicity
G = nx.from_pandas_edgelist(df.rename(columns={'distance':'weight'}), 'i', 'j', 'weight', 
                            create_using=nx.DiGraph)

I've added some more edges so the plot seems a little clearer:

G.edges(data=True)
# OutEdgeDataView([(1, 2, {'weight': 6000}), (1, 4, {'weight': 3200}), (1, 3, {'weight': 4000}), 
#                  (2, 3, {'weight': 1000}), (2, 6, {'weight': 5000}), (4, 8, {'weight': 4000}), 
#                  (6, 7, {'weight': 3000})])

We can define a dictionary for the edge colors, and a list for the nodes' color as:

path =  [1, 2, 6, 7]
path_edges = set(zip(path[:-1], path[1:]))

# set edge colors
edge_colors = dict()
for edge in G.edges():
    if edge in path_edges:
        edge_colors[edge] = 'magenta'
        continue
    else:
        edge_colors[edge] = 'lightblue'

nodes = G.nodes()
node_colors = ['orange' if i != 6 else 'lightgreen' for i in nodes]

Which we could use to plot the graph as:

fig = plt.figure(figsize=(12,8))
pos = nx.spring_layout(G, scale=20)
nx.draw(G, pos, 
        nodelist=nodes,
        node_color=node_colors,
        edgelist=edge_colors.keys(), 
        edge_color=edge_colors.values(),
        node_size=800,
        width=4,alpha=0.6,
        arrowsize=20,
        with_labels=True)



来源:https://stackoverflow.com/questions/61815687/set-a-different-color-for-a-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!