首页 > 解决方案 > 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

enter image description here

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:

enter image description here

The problem is that is very different from the graphs that appear on internet:

enter image description here

How can I do a graph similar to that one using NetworkX?

标签: pythonnetworkxgraph-theorydiscrete-mathematics

解决方案


要扩展评论,您需要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)

在此处输入图像描述


推荐阅读