Python Networkx:在指定节点位置时边没有采用正确的颜色
Python Networkx: edges not taking proper color, while specifying node positions
我是 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"]))
但是,输出中的问题仍然存在。
确实如你所说的边缘颜色是由边缘的值决定的,因为edge_color
数值通过指定的[=13]映射到颜色=].这里造成混淆的是坐标的具体排列,因为连接 (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)
我是 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"]))
但是,输出中的问题仍然存在。
确实如你所说的边缘颜色是由边缘的值决定的,因为edge_color
数值通过指定的[=13]映射到颜色=].这里造成混淆的是坐标的具体排列,因为连接 (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)