Python Networkx:在指定节点位置时,边缘未采用适当的颜色

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

我是Python的新手,开始学习networkx来绘制图形或道路网络。我必须指定节点位置。边缘颜色应取决于边缘的值。我尝试使用pandas数据框生成边缘。如果未指定位置,则边缘颜色可以正常工作。附带示例。

未指定职位时

# Build a dataframe with your connections
df = pd.DataFrame({ 'from':['A', 'B', 'C','A'], 'to':['D', 'A', 'E','C'], 'value':[1, 10, 5, 5]})
df

# Build your graph
G=nx.from_pandas_edgelist(df, 'from', 'to', create_using=nx.Graph() )

# Custom the nodes:
nx.draw(G, with_labels=True, node_color='skyblue', node_size=1500, edge_color=df['value'], width=10.0, edge_cmap=plt.cm.Blues)

这里的边缘颜色很完美

enter image description here

指定职位时

pos = {'A': (0,1), 'D': (1,2) , 'B': (2,3) , 'C': (6,5), 'E': (0,0)}

nx.draw(G, pos, with_labels=True, node_color='skyblue', node_size=1500, edge_color=df['value'], width=10.0, edge_cmap=plt.cm.Blues)

这里的节点位置是完美的,但是根据值的边缘颜色是错误的:

enter image description here

我也尝试过如下放置位置-

df2 = pd.DataFrame({ "Nodes": ['A','D','B','C','E'], "x": [0,1,2,6,0], "y": [1,2,3,5,0]})
for i in df2.index:
    G.add_node(df2.loc[i, "Nodes"], df2=(nodes.loc[i, "x"], df2.loc[i, "y"]))

但是,输出中的问题仍然相同。

python pandas networkx
1个回答
0
投票

实际上是您所说的边缘颜色is由边缘的值决定,因为edge_color数值通过指定的edge_cmap映射到颜色。这里引起混乱的是坐标的具体安排,因为连接(A,D)的边与连接(A,B)的边重叠:

pos = {'A': (0,1), 'D': (1,2) , 'B': (2,3) , 'C': (6,5), 'E': (0,0)}

enter image description here

如果稍微改变D的坐标,您将看到边缘具有预期的颜色:

pos = {'A': (0,1), 'D': (4,1) , 'B': (2,3) , 'C': (6,5), 'E': (0,0)}

nx.draw(G, pos, 
        with_labels=True, 
        node_color='skyblue', 
        node_size=1500, 
        edge_color=df['value'], 
        width=10.0, 
        edge_cmap=plt.cm.Blues)

enter image description here

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