为NetworkX中的每个路径指定颜色

问题描述 投票:1回答:1

我有车,城市和路线,每个城市是一个节点,每个路线是一个车产生的路径。

不同的汽车会有不同的路径,有时路径可能会相交(这意味着不同的汽车在它们的路径上发现了同一个城市),有时不会。

我想把所有的城市和不同的路径画成一个图,然后用plotly来绘制这个图。

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

使用 networkx.classes.function.add_path。 我不能实现这个功能,因为我不会保存不同车辆的信息,只有连接节点的列表。

As in the previous example add_path, G.edges(): [(CityA-CityB),(CityB-CityD),(CityZ-CityA),(CityA-CityK)]

我不知道我想要的东西是否可以用Networkx来实现.

一个解决方案是将列表传给plotly,但这样做我甚至不会使用NetworkX,下一步是分析图。

python graph plotly data-science networkx
1个回答
0
投票

你可以在NetworkX中设置节点和边缘的属性,然后你可以用这些属性来定制绘图的某些方面。在这种情况下,你可以给图形的边缘设置一个颜色属性,然后用这个属性来设置图形的颜色。edge_colornx.draw. 下面是你如何用你分享的路径示例来做这件事。

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']

现在创建一个有向图,并迭代路径列表, 并分配颜色添加他们作为边缘,相应的属性。

G = nx.DiGraph()
for path, color in zip(paths, colors):
    for edge in zip(path[:-1], path[1:]):
        G.add_edge(*edge, color=color)

你可以得到所有边缘的属性值。

edge_colors = nx.get_edge_attributes(G, 'color')

现在在绘制时,你可以设置边缘的颜色,通过:"我 "来设置。edge_color 争论。

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)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.