如何正确使用方法nx.check\u networkx的平面性?

2024-10-03 04:34:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要什么?

我有一个有很多顶点和很多边的图。顶点是协调的。 我试图检查图形的平面性,我总是得到真实的答案

示例

下面是一个小例子:

pos = {1: (0, 0), 2: (0, 1), 3: (1, 1), 4: (1, 0)}
    G = nx.Graph().to_undirected()
    G.add_nodes_from(pos)
    G.add_edge(1, 3, weight=1)
    G.add_edge(2, 4, weight=1)
    G.add_edge(2, 3, weight=1)
    print(nx.check_planarity(G, False))
    nx.draw_networkx(G, with_labels=True, pos=pos)
    plt.show()

输出为:

(True, <networkx.algorithms.planarity.PlanarEmbedding object at 0x07CD3E30>)

Graph

正如您可以清楚地看到的,图形不是平面性的,但是结果仍然是True

我在干什么?


Tags: 答案posnetworkxaddtrue图形示例例子
2条回答

您可以使用检查平面性的答案来绘制可能的平面布局

import networkx as nx
import matplotlib.pyplot as plt

pos = {1: (0, 0), 2: (0, 1), 3: (1, 1), 4: (1, 0)}
G = nx.Graph().to_undirected()
G.add_nodes_from(pos)
G.add_edge(1, 3, weight=1)
G.add_edge(2, 4, weight=1)
G.add_edge(2, 3, weight=1)

is_planar, G2 = nx.check_planarity(G, False)
print(is_planar)

# plotting

fig = plt.figure()
ax = fig.add_subplot(121)
ax = plt.gca()
ax.margins(0.20)

nx.draw_networkx(G, with_labels=True, pos=pos)

ax = fig.add_subplot(122)
ax = plt.gca()
ax.margins(0.20)

nx.draw_networkx(G2, with_labels=True)

plt.show()

请注意,如果图形可以在欧几里德平面上绘制,且没有任何边交点,则图形是平面的。
在您的情况下,图形是平面的,因为交换节点1和4就足以避免边缘相交。
但是,如果你考虑一个完整的图(一个完整的图{{CD1}}是平面的,仅为^ {CD2}}),你可以看到不同。p>

>>> K4 = nx.complete_graph(4)
>>> nx.check_planarity(K4)
(True, <networkx.algorithms.planarity.PlanarEmbedding object at 0x1035df1d0>)
>>> K5 = nx.complete_graph(5)
>>> nx.check_planarity(K5)
(False, None)

相关问题 更多 >