【问题标题】:How to draw weight labels with networkx and matplotlib?如何使用 networkx 和 matplotlib 绘制权重标签?
【发布时间】:2019-09-17 00:17:39
【问题描述】:

我正在研究图表,所以我正在尝试使用 networkx 和 matplotlib 在 python 中给定字典绘制图表,这是我的代码:

import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
graph = {
    "A":["B","C"],
    "B":["D","E"],
    "C":["E","F"],
    "D":["B","G"],
    "E":["B","C"],
    "F":["C","G"],
    "G":["D","F"]
}
x=10
for vertex, edges in graph.items():
    G.add_node("%s" % vertex)
    x+=2
    for edge in edges:
        G.add_node("%s" % edge)
        G.add_edge("%s" % vertex, "%s" % edge, weight = x)
        print("'%s' it connects with '%s'" % (vertex,edge))
nx.draw(G,with_labels=True)

plt.show()

我已经尝试过功能 draw_networkx_edge_labels 但似乎我需要一个我没有的位置,因为我动态添加节点,所以我需要一种方法来绘制适合我的边缘标签当前的实现。

【问题讨论】:

    标签: python-3.x matplotlib networkx graph-theory


    【解决方案1】:

    在添加完所有节点后绘制图形,以便根据它们计算位置并使用nx.draw_networkx_edge_labels(...)

    import networkx as nx
    import matplotlib.pyplot as plt
    G = nx.Graph()
    graph = {
        "A":["B","C"],
        "B":["D","E"],
        "C":["E","F"],
        "D":["B","G"],
        "E":["B","C"],
        "F":["C","G"],
        "G":["D","F"]
    }
    x=10
    for vertex, edges in graph.items():
        G.add_node("%s" % vertex)
        x+=2
        for edge in edges:
            G.add_node("%s" % edge)
            G.add_edge("%s" % vertex, "%s" % edge, weight = x)
            print("'%s' it connects with '%s'" % (vertex,edge))
    # ---- END OF UNCHANGED CODE ----
    
    # Create positions of all nodes and save them
    pos = nx.spring_layout(G)
    
    # Draw the graph according to node positions
    nx.draw(G, pos, with_labels=True)
    
    # Create edge labels
    labels = {e: str(e) for e in G.edges}
    
    # Draw edge labels according to node positions
    nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-10
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      相关资源
      最近更新 更多