import networkx as nx
import panel as pn
pn.extension(sizing_mode="stretch_width")
The purpose of this example is to show how easy it is to use NetworkX with Panel. For this example to work you will need NetworkX>=2.5
and pygraphviz
installed.
If you want interactive NetworkX graphs we recommend using HvPlot. See the HvPlot NetworkX User Guide.
This section is independent of Panel. You can find a tutorial and examples in the NetworkX Documentation.
We create the graph via NetworkX. We transform the NetworkX graph to a SVG using pygraphviz.
def clean_svg(svg):
"""To display a SVG in Panel nicely we need to
- remove any html in front of the `<svg` tag.
- replace the fixed width and height
- make the fill transparent
"""
viewbox_start = svg.find("viewBox=")
return '<svg height="100%"' + svg[viewbox_start:].replace('fill="white"','fill="transparent"')
def get_graph(nodes=5):
graph = nx.complete_graph(nodes)
pyviz_graph = nx.nx_agraph.to_agraph(graph)
svg_graph = pyviz_graph.draw(prog='dot', format='svg').decode('utf-8')
return clean_svg(svg_graph)
pn.pane.SVG(get_graph(), height=500)
Panel recognizes and shows clean svg
images out of the box.
nodes=pn.widgets.IntSlider(value=5, start=2, end=7, name="Number of Nodes")
get_graph = pn.bind(get_graph, nodes=nodes)
create_graph_component = pn.Row(pn.Spacer(), pn.panel(get_graph, height=500), pn.Spacer())
component = pn.Column(nodes, create_graph_component, height=600)
component
You can serve the app with panel serve NetworkX.ipynb
and find the live app at http://localhost:5006/NetworkX
ACCENT_BASE_COLOR="#98b2d1"
pn.template.FastListTemplate(
site="Panel",
site_url="https://panel.holoviz.org/_static/logo_horizontal.png",
title="NetworkX - Basic Example",
main=[component], header_background=ACCENT_BASE_COLOR, accent_base_color=ACCENT_BASE_COLOR,
theme_toggle=False,
).servable();