gpt4 book ai didi

python-3.x - 如何使用 networkx 和 matplotlib 绘制重量标签?

转载 作者:行者123 更新时间:2023-12-05 09:12:32 30 4
gpt4 key购买 nike

我正在研究图形,所以我尝试使用 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 但似乎我需要一个位置,因为我动态添加节点后我没有这个位置,所以我需要一种方法来绘制适合我的边缘标签当前实现。

最佳答案

在添加所有节点后绘制图形,以便计算位置并根据它们使用 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()

enter image description here

关于python-3.x - 如何使用 networkx 和 matplotlib 绘制重量标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57965825/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com