Rendering a graph
In this section, we will discuss how to render a VisualizationGraph object
to display the graph visualization.
If you have not yet created a VisualizationGraph object, refer to one of the following sections:
-
Getting started for creating a visualization graph from scratch using
neo4j-vizprimitives like Node and Relationship andVisualizationGraphdirectly. -
Visualizing existing data for importing data from a Pandas DataFrame or Neo4j GDS projection.
The render_widget method
Once you have a VisualizationGraph object, you can display it using the render_widget method.
This returns a GraphWidget, an interactive widget with two-way sync between Python and the browser, that works in
JupyterLab, Notebook 7, VS Code, and Colab.
All parameters of the render_widget method are optional, and the full list of them is listed in the API
reference: neo4j_viz.VisualizationGraph.render_widget().
The most important parameters to be aware of are the width and height parameters, which control the size of
the widget.
You can provide these either as a percentage of the available space (eg. "80%"), or as an absolute pixel value
(eg. "800px").
Further you can change the layout of the graph using the layout parameter, which can be set to one of the following values:
-
Layout.FORCE_DIRECTED- Nodes are arranged using the d3-force algorithm. It has no tunable options: the force-directed layout_options (gravity,simulationStopVelocity,seedingMethod,clustering) only apply toLayout.GPU_FORCE, and the wrapper warns if you set them here. -
Layout.GPU_FORCE- Nodes are arranged using NVL’s GPU-accelerated force simulation, and is the layout that supports clustering of connected nodes. It works with anyrenderer, but needs WebGL2 support in the browser; where that is missing, NVL falls back toLayout.FORCE_DIRECTEDand clustering is ignored. To customize the layout, use ForceDirectedOptions via layout_options. -
Layout.HIERARCHICAL- Arranges nodes by the directionality of their relationships, creating a tree-like structure. To customize the layout use HierarchicalLayoutOptions via layout_options. It also supports clustering, via theclusterByoption. -
Layout.COORDINATE- Arranges nodes based on coordinates defined in x and y properties on each node.
Another thing of note is the max_allowed_nodes parameter, which controls the maximum number of nodes that is allowed
for the graph to contain in order to be rendered.
It defaults to 10.000, because rendering a large number of nodes can be slow and unresponsive.
However, you can increase this value if you are confident that your environment can handle the scale.
In this case you might also want to pass Renderer.WEB_GL as the renderer to improve performance, at the cost of
captions (the WebGL renderer does not render them; the canvas renderer does).
Clustering nodes
The Layout.GPU_FORCE and Layout.HIERARCHICAL layouts can group nodes into clusters. Nodes that share the same
value for a chosen node property are placed together, and the GPU force layout can additionally draw an outline or a
halo around each cluster.
Clustering is configured through the layout_options parameter, using ClusteringOptions inside
ForceDirectedLayoutOptions for the GPU force layout:
from neo4j_viz import ClusteringOptions, ForceDirectedLayoutOptions, Layout
VG.render_widget(
layout=Layout.GPU_FORCE,
layout_options=ForceDirectedLayoutOptions(
clustering=ClusteringOptions(clusterBy="community", drawOutline=True, drawHalo=True),
),
)
Here each node’s community property determines its cluster; nodes without the property are left unclustered.
Coloring the nodes by the same property (see customizing.adoc#coloring-the-graph) makes the clusters easy to
tell apart, and the halo is only drawn when all nodes in a cluster share one color.
The GPU force layout works with any renderer, including the default canvas renderer, so captions are kept.
If you switch to Renderer.WEB_GL for draw performance, note that the WebGL renderer does not render captions.
|
For the hierarchical layout, clustering is enabled directly with the clusterBy option:
from neo4j_viz import HierarchicalLayoutOptions, Layout
VG.render_widget(
layout=Layout.HIERARCHICAL,
layout_options=HierarchicalLayoutOptions(clusterBy="community"),
)
Relationships whose source or target is not part of the graph’s nodes ("dangling" relationships) cannot be
drawn, and a graph containing them may appear empty.
By default render_widget emits a warning that lists the offending relationships so the problem is not silent.
You can change this with the on_dangling parameter: pass "error" to raise a ValueError instead, or "none"
to skip the check entirely.
Unlike render, the widget also lets you update the graph after it has been displayed, for example to add nodes and
relationships, to change the layout or zoom, or to react to the user’s selections and clicks.
Refer to Customizing the visualization for these methods.
Examples
Refer to the Getting started and the tutorials for
examples of render_widget method usage.
The render method
The render method returns an IPython.display.HTML object containing the graph as static HTML.
It is not recommended for interactive use; use render_widget instead.
Reach for render when you need to embed the graph in a document or web page, or to
export it to an HTML file.
It accepts the same width, height, layout, max_allowed_nodes, and on_dangling parameters as render_widget.
The full list of parameters of the render method is listed in the API
reference: neo4j_viz.VisualizationGraph.render().
Using with Streamlit
There are two ways to display a graph in a Streamlit app.
Static rendering
The HTML object returned by render can be embedded directly. Pass its data
attribute to st.iframe:
import streamlit as st
from neo4j_viz import VisualizationGraph
st.iframe(VG.render(height="600px").data, height=600)
This is the simplest option and fully supports the in-canvas interactions (pan, zoom, selection, layout switching), but nothing is communicated back to Python.
Interactive widget with two-way sync
To read interactions such as the current selection back in Python, use
neo4j_viz.streamlit.display_widget. It renders the same interactive widget as
render_widget does in a notebook and syncs the selected and options state
back into the GraphWidget you pass in (in place) on each rerun.
This requires the streamlit optional dependency (Streamlit 1.58 or newer):
pip install neo4j-viz[streamlit]
import streamlit as st
from neo4j_viz.streamlit import display_widget
widget = VG.render_widget()
display_widget(widget, key="my-graph")
selection = widget.selected
st.write("Selected node IDs:", selection.nodeIds)
display_widget takes a GraphWidget (as returned by
VisualizationGraph.render_widget()), so you can configure the widget with all
the usual options (layout, initial_zoom, height, …) when building it.
When displaying more than one graph in an app, give each a unique key.
Exporting to HTML
The object returned by the render method is a IPython.display.HTML object.
In addition to being displayed in a Jupyter notebook or streamlit application, it can also be saved as an HTML file.
This could be useful if you want to share the visualization with others or embed it in a web page.
To save the HTML data to a file, you can use the data attribute of the HTML object:
html = VG.render(...)
with open("my_graph.html", "w") as f:
f.write(html.data)
Saving as PNG or SVG
The interactive widget can save the current visualization as a PNG or SVG image file. The image is rendered by the widget frontend in the browser, so the widget must be displayed in a notebook cell first:
widget = VG.render_widget()
widget
Then the current visualization can be saved from a later cell:
await widget.save("my_graph.svg")
await widget.save("my_graph.png", background_color="#ffffff")
save waits for the widget frontend to finish rendering, including the initial layout, before sending the request, so it is safe to call it in the same cell that displays the widget, or immediately after.
The format is inferred from the file extension (.png or .svg) and defaults to SVG when the file has no extension; any other extension is rejected.
An explicit format="png"/format="svg" argument must match the extension.
A PNG captures the current view (the canvas at its rendered size, including the current zoom and pan), while an SVG always contains the entire graph.
The image is rendered by the widget frontend in the browser, so save must be await-ed while the widget is displayed in a live notebook (JupyterLab, Notebook, VS Code, Colab, or marimo). Outside a running kernel, for example in a plain Python script, there is no renderer and saving raises an error — use Exporting to HTML there instead. The frontend must also be able to render: if the widget’s output is scrolled out of view or collapsed, or its browser tab is in the background, save raises a timeout error.
|