简体   繁体   English

如何使用networkx和matplotlib绘制重量标签?

[英]How to draw weight labels with networkx and matplotlib?

Im studying graphs so I'm trying to draw a graph given a dictionary in python using networkx and matplotlib, this is my code: 我正在研究图,所以我试图使用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()

I already tried the function draw_networkx_edge_labels but seems like I need a position for that which I dont have since I add the nodes dynamically, so I need a way to draw the edges labels which fit with my current implementation. 我已经尝试过函数draw_networkx_edge_labels,但是由于我动态添加节点,因此我似乎需要一个我没有的位置,因此我需要一种方法来绘制适合当前实现的边缘标签。

You draw the graph after all nodes are added so you can calculate positions and use nx.draw_networkx_edge_labels(...) according to them: 添加完所有节点后即可绘制图形,以便可以计算位置并根据它们使用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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM