-
Notifications
You must be signed in to change notification settings - Fork 114
/
Copy path01.3D_Graph_Visualization.py
71 lines (59 loc) · 2.11 KB
/
01.3D_Graph_Visualization.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
import plotly.graph_objects as go
def is_graph_planar(graph):
return len(graph.edges()) <= 3 * len(graph.nodes()) - 6
def draw_graph_2d(graph, title):
pos = nx.spring_layout(graph, seed=42)
nx.draw(graph, pos, with_labels=True, node_size=2000, node_color='skyblue', font_size=10, font_weight='bold')
plt.title(title)
plt.show()
def draw_graph_3d(graph, title):
pos = nx.spring_layout(graph, dim=3, seed=42)
edge_x = []
edge_y = []
edge_z = []
for edge in graph.edges():
x0, y0, z0 = pos[edge[0]]
x1, y1, z1 = pos[edge[1]]
edge_x.extend([x0, x1, None])
edge_y.extend([y0, y1, None])
edge_z.extend([z0, z1, None])
edge_trace = go.Scatter3d(
x=edge_x, y=edge_y, z=edge_z,
line=dict(width=1, color='grey'),
mode='lines'
)
node_x = []
node_y = []
node_z = []
for node in graph.nodes():
x, y, z = pos[node]
node_x.append(x)
node_y.append(y)
node_z.append(z)
node_trace = go.Scatter3d(
x=node_x, y=node_y, z=node_z,
mode='markers+text',
marker=dict(size=8, line=dict(width=2), color='red'),
text=[f'Node {node}' for node in graph.nodes()],
textposition='bottom center'
)
fig = go.Figure(data=[edge_trace, node_trace])
fig.update_layout(title=title, showlegend=False)
fig.show()
# Example 1: Check if K5 is non-planar
K5 = nx.complete_graph(5)
print(f"Is K5 non-planar? {not is_graph_planar(K5)}")
draw_graph_2d(K5, "K5 (2D Visualization)")
draw_graph_3d(K5, "K5 (3D Visualization)")
# Example 2: Check if the given graphs are non-planar
G1 = nx.Graph([(1, 2), (1, 3), (2, 3), (3, 4), (5, 4)])
G2 = nx.Graph([(1, 2), (1, 3), (1, 4), (5, 2), (5, 3), (5, 4)])
print(f"Is G1 non-planar? {not is_graph_planar(G1)}")
draw_graph_2d(G1, "Graph G1 (2D Visualization)")
draw_graph_3d(G1, "Graph G1 (3D Visualization)")
print(f"Is G2 non-planar? {not is_graph_planar(G2)}")
draw_graph_2d(G2, "Graph G2 (2D Visualization)")
draw_graph_3d(G2, "Graph G2 (3D Visualization)")