我是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)
这里的边缘颜色很完美
指定职位时
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)
这里的节点位置是完美的,但是根据值的边缘颜色是错误的:
我也尝试过如下放置位置-
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"]))
但是,输出中的问题仍然相同。
实际上是您所说的边缘颜色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)}
如果稍微改变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)