python-3.x 对图的顶点进行重新排序,它应该像Petersen图那样排序

yxyvkwin  于 2023-01-06  发布在  Python
关注(0)|答案(2)|浏览(153)

我有下一个代码:

import networkx

grafoPetersen = {
    1: [2,5,6], 
    2: [3,1,7], 
    3: [4,2,8], 
    4: [5,3,9], 
    5: [1,4,10],
    6: [1,8,9], 
    7:[2,9,10], 
    8: [3,10,6], 
    9: [4,6,7], 
    10: [5,7,8]
}

for k in grafoPetersen:
    grafoPetersen[k].append(-1)
    grafoPetersen[k].append(-2)
grafoPetersen[-1] = list(range(1,11))
grafoPetersen[-2] = list(range(1,11))

rutaHamiltoniana = [8, 3, 4, 5, 10, 7, 2, 1, 6, 9];
g = networkx.Graph()
for k, vs in grafoPetersen.items():
    for v in vs:
        if v in [-1, -2] or k in [-1, -2]:
            continue
        if abs(rutaHamiltoniana.index(k) - rutaHamiltoniana.index(v)) == 1:
            g.add_edge(k,v, color='red', width=1.5)
        else:
            g.add_edge(k,v, color='black', width=0.5)

posicion = networkx.circular_layout(g)
edges = g.edges()
colores = [g[u][v]['color'] for u,v in edges]
anchuras = [g[u][v]['width'] for u,v in edges]
networkx.draw(g, posicion, edges=edges, edge_color=colores, width=anchuras, with_labels = True)

我得到的输出如下:

我的图是彼得森的图,我想这样显示:

但与我在第一幅中设置的风格相同。
我试过了:

options = {
    'with_labels': True,
    'node_color': 'black',
    'node_size': 200,
    'width': 3,
}
networkx.draw_shell(g, nlist=[range(5,10), range(5)], **options)

如下所示:How to show a graph like a Petersen's graph但我得到了几个错误。
你知道我怎样才能把第一个图片解析成第二个图片,同时保持第一个图片的样式吗?

**EDIT 1:**以下是如何获取Petersen图的路径并将其绘制为第一个图的完整代码:Hamiltonian path inside Petersen's graph algorithm

yeotifhr

yeotifhr1#

nlist中的列表定义了要放置在同心圆(壳)上的节点分组。节点由我们在grafoPetersen中定义的ID定义:一、二、...、十

networkx.draw_shell(g, nlist=[range(5,10), range(5)])

此调用将节点range(5,10)=[5,6,7,8,9]分组在一个同心圆上,将range(5)=[0,1,2,3,4]分组在第二个同心圆上。但是,在grafoPetersen中没有定义ID为0的节点。此外,我们定义了ID为10的节点,这两个范围都不表示该节点。
为了解决这个问题,我们必须调整范围:

networkx.draw_shell(g, nlist=[range(6,11), range(1,6)])

还有各种各样的选择

networkx.draw_shell(g, nlist=[range(6,11), range(1,6)], edge_color=colors, width=widths)

dhxwm5r4

dhxwm5r42#

import networkx as nx
import matplotlib.pyplot as plt

# rutaHamiltoniana = [8, 3, 4, 5, 0, 7, 2, 1, 6, 9]

fig = plt.figure(1, figsize=(8, 7), dpi=60)
G = nx.petersen_graph()
shells = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
pos = nx.shell_layout(G, shells)
nx.draw(G, pos=pos, node_color="red", with_labels=True)
nx.draw_networkx_edges(
    G,
    pos = pos,
    # list of tuples for hamiltonian path, not list !!!!!
    edgelist = [(8,3), (3,4), (4,5), (5,0), (0,7), (7,2), (2,1), (1,6), (6,9), (9,8)],
    width=8,
    alpha=0.5,
    edge_color="blue"
)

相关问题