# Vizro is an open-source toolkit for creating modular data visualization applications.
# check out https://github.com/mckinsey/vizro for more info about Vizro
# and checkout https://vizro.readthedocs.io/en/stable/ for documentation.
import vizro.plotly.express as px
from vizro import Vizro
import vizro.models as vm
df = px.data.iris()
import plotly.graph_objects as go
import networkx as nx
from vizro.models.types import capture
import pandas as pd
df = pd.read_csv("node.csv")
@capture("graph")
def custom_chart(data_frame):
# Create a directed graph from the DataFrame
G = nx.from_pandas_edgelist(
data_frame.dropna(subset=["node_1"]), # Ensure node_1 is not NaN
source="node_1",
target="node_2",
create_using=nx.DiGraph(), # Directed graph
)
# Create layout for nodes
pos = nx.spring_layout(G)
# Create edge trace
edge_trace = go.Scatter(
x=[], y=[], line=dict(width=1, color="#888"), hoverinfo="none", mode="lines"
)
for edge in G.edges():
x0, y0 = pos[edge[0]]
x1, y1 = pos[edge[1]]
edge_trace["x"] += (x0, x1, None)
edge_trace["y"] += (y0, y1, None)
# Create node trace
node_trace = go.Scatter(
x=[],
y=[],
text=[],
mode="markers+text",
textposition="top center",
hoverinfo="text",
marker=dict(showscale=False, color=[], size=10, line_width=2),
)
for node in G.nodes():
x, y = pos[node]
node_trace["x"] += (x,)
node_trace["y"] += (y,)
node_trace["text"] += (node,)
# Create arrows for directed edges
annotations = []
for edge in G.edges():
x0, y0 = pos[edge[0]]
x1, y1 = pos[edge[1]]
annotations.append(
dict(
ax=x0,
ay=y0,
axref="x",
ayref="y",
x=x1,
y=y1,
xref="x",
yref="y",
showarrow=True,
arrowhead=2,
arrowsize=1.5,
arrowwidth=1,
arrowcolor="#888",
)
)
# Create figure
fig = go.Figure(
data=[edge_trace, node_trace],
layout=go.Layout(
title="<br>Network graph made with Python",
showlegend=False,
hovermode="closest",
margin=dict(b=20, l=5, r=5, t=40),
annotations=annotations,
xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
yaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
),
)
return fig
page = vm.Page(
title="Vizro on PyCafe",
components=[
vm.Graph(id="hist_chart", figure=custom_chart(
data_frame=df,
),
),
],
)
dashboard = vm.Dashboard(pages=[page])
Vizro().build(dashboard).run()