Spaces:
Running
Running
File size: 1,438 Bytes
c858478 | 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 72 73 74 75 76 77 78 79 | import plotly.graph_objects as go
import networkx as nx
def visualize_graph(G):
pos = nx.spring_layout(G, seed=42)
edge_x = []
edge_y = []
edge_text = []
for u, v, data in G.edges(data=True):
x0, y0 = pos[u]
x1, y1 = pos[v]
edge_x += [x0, x1, None]
edge_y += [y0, y1, None]
edge_text.append(data["label"])
edge_trace = go.Scatter(
x=edge_x,
y=edge_y,
line=dict(width=1),
hoverinfo='none',
mode='lines'
)
node_x = []
node_y = []
node_text = []
for node in G.nodes():
x, y = pos[node]
node_x.append(x)
node_y.append(y)
node_text.append(node)
node_trace = go.Scatter(
x=node_x,
y=node_y,
mode='markers+text',
text=node_text,
textposition="top center",
hoverinfo='text',
marker=dict(size=20)
)
fig = go.Figure(data=[edge_trace, node_trace])
fig.update_layout(
showlegend=False,
hovermode='closest',
margin=dict(b=20, l=5, r=5, t=40)
)
for u, v in G.edges():
x0, y0 = pos[u]
x1, y1 = pos[v]
fig.add_annotation(
x=x1,
y=y1,
ax=x0,
ay=y0,
xref='x',
yref='y',
axref='x',
ayref='y',
showarrow=True,
arrowhead=4,
arrowsize=2.5,
arrowwidth=2.5,
arrowcolor="black",
opacity=0.9
)
return fig
|