python - Königsberg Bridges using Networkx
问题描述
I am trying to plot the graph of the famous problem of Königsberg Bridges using NetworkX and Python 3.8
This the code I am using:
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
G=nx.Graph()
G.add_node(1) ## Land A
G.add_node(2) ## Land B
G.add_node(3) ## Land C
G.add_node(4) ## Land D
## Connected Edges
G.add_edge(1,3,color='r',weight=1) ## Bridge 1
G.add_edge(1,3,color='r',weight=1) ## Bridge 2
G.add_edge(1,4,color='r',weight=1) ## Bridge 3
G.add_edge(3,4,color='r',weight=1) ## Bridge 4
G.add_edge(1,2,color='r',weight=1) ## Bridge 5
G.add_edge(1,2,color='r',weight=1) ## Bridge 6
G.add_edge(2,4,color='r',weight=1) ## Bridge 7
colors = nx.get_edge_attributes(G,'color').values()
weights = nx.get_edge_attributes(G,'weight').values()
names = {1:"Land A",2:"Land B",3:"Land C",4:"Land D"}
H=nx.relabel_nodes(G,names)
pos = nx.circular_layout(H)
nx.draw_networkx(H,pos,edge_color=colors,width=list(weights))
plt.savefig("konigsberg_bridges_graph.png")
plt.show()
and the Graph generated is this one:
The problem is that is very different from the graphs that appear on internet:
How can I do a graph similar to that one using NetworkX?
解决方案
要扩展评论,您需要MultiGraph
在两个节点之间使用多个边:
G=nx.MultiGraph()
G.add_node(1) ## Land A
G.add_node(2) ## Land B
G.add_node(3) ## Land C
G.add_node(4) ## Land D
## Connected Edges
G.add_edge(1,3,color='r',weight=1) ## Bridge 1
G.add_edge(1,3,color='r',weight=1) ## Bridge 2
G.add_edge(1,4,color='r',weight=1) ## Bridge 3
G.add_edge(3,4,color='r',weight=1) ## Bridge 4
G.add_edge(1,2,color='r',weight=1) ## Bridge 5
G.add_edge(1,2,color='r',weight=1) ## Bridge 6
G.add_edge(2,4,color='r',weight=1) ## Bridge 7
colors = nx.get_edge_attributes(G,'color').values()
weights = nx.get_edge_attributes(G,'weight').values()
names = {1:"Land A",2:"Land B",3:"Land C",4:"Land D"}
H=nx.relabel_nodes(G,names)
要可视化网络,您可以使用显示平行边的 Graphviz。您可以将图表写入dot
并显示图表graphviz.Source
:
path = 'multig.dot'
nx_pydot.write_dot(H, path)
Source.from_file(path)
推荐阅读
- .htaccess - 尝试缓存半身像时,从查询字符串方法移开后,样板无法获取 css/js
- ios - 为什么 viewDidLoad() 中不存在 TableView 的 FooterView 以及如何解决?
- python - ImportError:没有名为 Window 的模块,但来自导入工作
- python - Jupyter-notebook 在命令 conda install -c conda-forge 后爆炸
- node.js - 车把,每个都嵌套有平行阵列
- ios - 如何从呈现为半模态的视图控制器将视图控制器推送为全屏
- javascript - 快速排序 Lomuto 算法
- angularjs - ./ansi-html 1:0 中的错误模块解析失败:意外字符“#”(1:0)
- angular - 关闭按钮的 Jasmine 测试用例
- visual-studio-2017 - Visual Studio 调试菜单已禁用