【问题标题】:Python networkx graph labelsPython networkx 图标签
【发布时间】:2019-07-13 21:17:29
【问题描述】:

我有两个数据框,用于在 Python 中创建带有 networkx 的图形。数据框 df1(节点坐标)和 df2(边缘信息),如下所示:

    location     x      y
0   The Wall     145    570
2   White Harbor 140    480

    location    x             y 
56  The Wall    Winterfell    259 
57  Winterfell  White Harbor  247 

这是我为尝试绘制图表而实现的代码:

plt.figure()
G=nx.Graph()

for i, x in enumerate(df1['location']):
  G.add_node(x, pos=(df1['x'][i], df1['y'][i]))

for x, x2, w in zip(df2['location'], df2['x'], df2['y']):
  G.add_edge(x, x2, weight=w)

plt.figure(figsize=(15,15)) 

pos = nx.get_node_attributes(G, 'pos')
weights = nx.get_edge_attributes(G, 'weight') 
nx.draw(G, pos=pos, node_size=40, with_labels=True, fontsize=9)
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=weights)

plt.show()

我之前运行了几次,它似乎可以工作,但是现在重新打开 jupyter notebook 并再次运行它之后,它就无法工作了。我主要有两个主要问题。

  • 如果我尝试只运行 nx.draw(G, pos=pos, node_size=40, with_labels=True, fontsize=9) 行,我的图表会显示,但不会显示任何标签,即使 with_labels 设置为 true。
  • 其次,这一行 nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=weights) 现在向我显示错误无法将序列乘以“浮点”类型的非整数

我已经看了几个小时了,但我似乎无法修复它,有什么想法吗?


编辑: 如果从 nx.draw 中排除 pos=pos,我可以显示标签,但如果我包含它,它将不起作用

【问题讨论】:

    标签: python graph networkx


    【解决方案1】:

    问题是您没有为节点Winterfell 指定任何pos 属性,然后当您尝试在draw_networkx_edge_labels 中访问它时找不到它。

    如果你尝试给它一个位置属性,比如说:

          location    x    y
    0      TheWall  145  570
    1   Winterfell  142  520
    2  WhiteHarbor  140  480
    

    那么就可以正确访问所有节点的属性,正确绘制网络:

    plt.figure()
    G=nx.Graph()
    
    df1 = df1.reset_index(drop=True)
    df2 = df2.reset_index(drop=True)
    
    for i, x in enumerate(df1['location']):
        G.add_node(x, pos=(df1.loc[i,'x'], df1.loc[i,'y']))
    
    for x, x2, w in zip(df2['location'], df2['x'], df2['y']):
        G.add_edge(x, x2, weight=w)
    
    plt.figure(figsize=(15,15)) 
    
    pos = nx.get_node_attributes(G, 'pos')
    weights = nx.get_edge_attributes(G, 'weight') 
    nx.draw(G, pos=pos, node_size=40, with_labels=True, fontsize=9)
    nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=weights)
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      • 2019-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多