ipycytoscape

Turn a networkx graph into an interactive, clickable network, with communities, shortest paths, and styles computed in Python and painted onto the live graph.

ipycytoscape wraps Cytoscape.js to turn a networkx graph into an interactive, clickable network, with communities, shortest paths, and other networkx analysis mapped onto size, color, and shape through a CSS-like stylesheet. Four accessors turn clicks and selections into reactive values, read the same way you’d read input.my_slider().

hero

Clicking a character fades everyone outside their circle while a detail card lists their top co-stars. Try the app.

Installation

pip install 'shinywidgets[ipycytoscape]'

This installs ipycytoscape itself. Building graphs from networkx also needs pip install networkx (not a hard dependency of the extra, since the renderer also accepts a CytoscapeWidget you build yourself from other sources, e.g. Cytoscape JSON or a py2neo graph).

Quick start

import networkx as nx
from shiny.express import ui
from shinywidgets import render_ipycytoscape

ui.page_opts(title="Zachary's karate club", fillable=True)

with ui.card(full_screen=True):

    @render_ipycytoscape
    def network():
        return nx.karate_club_graph()

quickstart

Returning a plain networkx graph is enough for a pannable, zoomable, draggable network: node ids become strings, node and edge attributes land in each element’s data, and DiGraph/MultiGraph get arrows and curved parallel edges automatically. The graph fills its card and tracks resizes, sidebar toggles, and full-screen mode. The renderer only auto-coerces networkx graphs; build from Cytoscape JSON, a pandas edge list (nx.from_pandas_edgelist()), or anything else via CytoscapeWidget(...) yourself and return that instead.

Overview

A look at what you can build. Click any of them to open the app, with its code, in Shinylive.

Cytoscape’s full stylesheet and layout vocabulary – more selectors, layouts, and visual properties than fit here – is in Cytoscape.js’s documentation.

Reacting to interaction

Every @render_ipycytoscape output has methods, called accessors, that report what the user did: network.clicked_node(), network.selected_nodes(), and more. Call one from any reactive context, the same way you’d call input.my_slider(), and that context re-runs whenever the user does it again.

Click a node for detail

import networkx as nx
from ipycytoscape import CytoscapeWidget
from shiny.express import render, ui
from shinywidgets import render_ipycytoscape

G = nx.karate_club_graph()

ui.page_opts(title="clicked_node()", fillable=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_ipycytoscape
        def network():
            widget = CytoscapeWidget(G)
            widget.set_layout(name="concentric")
            return widget

    with ui.card():
        ui.card_header("Clicked member")

        @render.ui
        def detail():
            clicked = network.clicked_node()
            if clicked is None:
                return ui.p("Click a member to see their connections.")
            member = int(clicked["data"]["id"])
            friends = sorted(G.neighbors(member))
            return ui.TagList(
                ui.h5(f"Member {member}"),
                ui.p(f"{G.nodes[member]['club']}'s faction"),
                ui.p(f"Connected to {len(friends)}: {', '.join(map(str, friends))}"),
            )

clicked_node() is None until the first click, then a dict with the clicked node’s cytoscape data. It attaches the moment the graph renders, so a click is never lost to timing, and it’s kept across a re-render until the user clicks the new graph.

Select a group

import networkx as nx
from ipycytoscape import CytoscapeWidget
from shiny.express import render, ui
from shinywidgets import render_ipycytoscape

G = nx.les_miserables_graph()
STYLE = [{"selector": "node:selected", "style": {"background-color": "#e15759"}}]

ui.page_opts(title="selected_nodes()", fillable=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):
        ui.card_header("Click a node, or shift-drag a box to select a group")

        @render_ipycytoscape
        def network():
            widget = CytoscapeWidget(
                G, auto_unselectify=False, box_selection_enabled=True
            )
            widget.set_style(STYLE)
            widget.set_layout(name="cose")
            for node in widget.graph.nodes:
                node.selectable = True  # ipycytoscape defaults nodes to unselectable
            return widget

    with ui.card():
        ui.card_header("Group stats")

        @render.ui
        def stats():
            selected = {d["id"] for d in network.selected_nodes()}
            if not selected:
                return ui.p("Nothing selected.")
            sub = G.subgraph(selected)
            return ui.p(
                f"{len(selected)} characters, {sub.number_of_edges()} ties inside "
                f"the group, density {nx.density(sub):.2f}"
            )

A click selects one node; shift-drag box-selects a group; clicking the background clears everything. selected_nodes() reports [] until something is selected, and re-seeds (rather than carries over) on every re-render, since it describes the graph’s current selection state. Box selection needs CytoscapeWidget(..., auto_unselectify=False, box_selection_enabled=True), and ipycytoscape defaults nodes to unselectable, so set node.selectable = True on each one, as above.

Highlight a neighborhood

Combining clicked_node() with a restyle effect gives you a “focus” interaction: fade everything except the clicked node and its neighbors, without ever re-running the layout.

import networkx as nx
from ipycytoscape import CytoscapeWidget
from shiny import reactive
from shiny.express import render, ui
from shinywidgets import render_ipycytoscape

G = nx.les_miserables_graph()
STYLE = [
    {"selector": "node", "style": {"background-color": "#447099"}},
    {"selector": "node[degree >= 15]", "style": {"label": "data(id)"}},
    {"selector": ".faded", "style": {"opacity": 0.1, "text-opacity": 0}},
    {"selector": "node.focus", "style": {"border-width": 3, "border-color": "#212529"}},
]
for n in G.nodes:
    G.nodes[n]["degree"] = G.degree(n)

ui.page_opts(title="Click to highlight a neighborhood", fillable=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_ipycytoscape
        def network():
            widget = CytoscapeWidget(G)
            widget.set_style(STYLE)
            widget.set_layout(name="concentric")
            return widget

    with ui.card():
        ui.card_header("Selected character")

        @render.ui
        def detail():
            clicked = network.clicked_node()
            if clicked is None:
                return ui.p("Click a character to see their circle.")
            name = clicked["data"]["id"]
            return ui.p(f"{name} and {G.degree(name)} co-characters are highlighted.")

    @reactive.effect
    def _():
        # Restyle in place by toggling classes: the layout never reruns and
        # the user's pan/zoom is kept
        clicked = network.clicked_node()
        center = clicked["data"]["id"] if clicked else None
        focus = {center, *G[center]} if center else set()
        for node in network.widget.graph.nodes:
            name = node.data["id"]
            if not focus:
                node.classes = ""
            else:
                node.classes = (
                    "focus" if name == center else "" if name in focus else "faded"
                )
        for edge in network.widget.graph.edges:
            s, t = edge.data["source"], edge.data["target"]
            edge.classes = "" if not focus or center in (s, t) else "faded"

For an app that combines clicking, selecting, and a shortest-path picker, start from the network explorer template.

Updating in place

When an input changes, the simplest thing is to let the render function re-run. For ipycytoscape that’s an expensive rebuild: every node and edge is its own ipywidget, so re-rendering tears all of them down, resets the camera to the layout’s default fit, and clears any classes you’ve set.

For everything else – restyling, toggling classes, switching layouts – don’t read the input in the render function. Instead, change the widget in place through network.widget from a @reactive.effect. This touches only what you change, and the user’s pan and zoom survive:

import networkx as nx
from ipycytoscape import CytoscapeWidget
from shiny import reactive
from shiny.express import input, ui
from shinywidgets import render_ipycytoscape

G = nx.les_miserables_graph()
STYLE = [
    {"selector": "node", "style": {"background-color": "#447099"}},
    {"selector": "node.highlight", "style": {"background-color": "#e15759"}},
]

ui.page_opts(title="In-place update vs. re-render", fillable=True)
ui.p("Scroll to zoom or drag to pan, then try each button.", class_="text-muted")
with ui.layout_columns(col_widths=[6, 6]):
    ui.input_action_button("highlight", "Highlight high-degree nodes (in place)")
    ui.input_action_button("rerender", "Re-render from scratch")

with ui.card(full_screen=True):

    @render_ipycytoscape
    def network():
        input.rerender()  # only this button forces a full rebuild
        widget = CytoscapeWidget(G)
        widget.set_style(STYLE)
        widget.set_layout(name="cose")
        return widget

    @reactive.effect
    @reactive.event(input.highlight)
    def _():
        # Toggles a class on each node: no re-render, no relayout, so the
        # user's current pan/zoom is untouched
        for node in network.widget.graph.nodes:
            node.classes = "highlight" if G.degree(node.data["id"]) >= 15 else ""

Switching layouts in place

widget.set_layout(name=...) re-runs a different layout algorithm without rebuilding the graph:

import networkx as nx
from ipycytoscape import CytoscapeWidget
from shiny import reactive
from shiny.express import input, ui
from shinywidgets import render_ipycytoscape

G = nx.les_miserables_graph()
LAYOUTS = ["cose", "concentric", "breadthfirst", "dagre"]

ui.page_opts(title="Layouts", fillable=True)
ui.input_select("layout", "Layout", LAYOUTS)

with ui.card(full_screen=True):

    @render_ipycytoscape
    def network():
        widget = CytoscapeWidget(G)
        with reactive.isolate():
            widget.set_layout(name=input.layout())
        return widget

    @reactive.effect
    def _():
        # Re-run the chosen layout in place; the graph is never re-rendered
        network.widget.set_layout(name=input.layout())
cose (force-directed) dagre (hierarchical)
cose dagre

set_layout() merges its keyword arguments onto the existing layout dict rather than replacing it, so switching name keeps any spacing options you’ve already set. Every layout change re-fits the viewport to the new arrangement and re-runs on the whole graph – there’s no incremental layout, which is fine at the graph sizes this widget is meant for.

Shortest path between two picks

A pair of input_selectize() values feeds nx.shortest_path(); the result is drawn by toggling a path class, not by re-rendering.

import networkx as nx
from ipycytoscape import CytoscapeWidget
from shiny import reactive
from shiny.express import input, render, ui
from shinywidgets import render_ipycytoscape

G = nx.les_miserables_graph()
CHARACTERS = sorted(G.nodes)
STYLE = [
    {"selector": "node", "style": {"background-color": "#447099"}},
    {"selector": "node.path", "style": {"label": "data(id)", "border-width": 3}},
    {"selector": "edge.path", "style": {"line-color": "#e15759", "width": 5}},
]

ui.page_opts(title="Shortest path, drawn in place", fillable=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_ipycytoscape
        def network():
            widget = CytoscapeWidget(G)
            widget.set_style(STYLE)
            widget.set_layout(name="cose")
            return widget

    with ui.card():
        ui.input_selectize(
            "ends",
            "Shortest path between",
            CHARACTERS,
            multiple=True,
            options={"maxItems": 2},
        )

        @render.ui
        def info():
            if len(input.ends()) != 2:
                return ui.p("Pick two characters.")
            return ui.p(" → ".join(path()))


@reactive.calc
def path() -> list[str]:
    ends = input.ends()
    if len(ends) != 2:
        return []
    return nx.shortest_path(G, *ends)


@reactive.effect
def _():
    # No re-render and no relayout: only each element's classes change
    p = set(path())
    on_path_edges = set(zip(path(), path()[1:])) | set(zip(path()[1:], path()))
    for node in network.widget.graph.nodes:
        node.classes = "path" if node.data["id"] in p else ""
    for edge in network.widget.graph.edges:
        key = (edge.data["source"], edge.data["target"])
        edge.classes = "path" if key in on_path_edges else ""

Filter, keep the layout

A force-directed layout is expensive to compute and meaningful positions take a moment to settle, so you don’t want to re-run it every time a filter changes. Hiding elements with a display: none style class – rather than removing them from the graph – keeps every remaining node exactly where it was.

import networkx as nx
from ipycytoscape import CytoscapeWidget
from shiny import reactive
from shiny.express import input, ui
from shinywidgets import render_ipycytoscape

G = nx.les_miserables_graph()
for n in G.nodes:
    G.nodes[n]["degree"] = G.degree(n)
STYLE = [
    {"selector": "node", "style": {"background-color": "#447099"}},
    {"selector": ".hidden", "style": {"display": "none"}},
]

ui.page_opts(title="Filter without losing the layout", fillable=True)
ui.input_slider("min_degree", "Minimum number of co-stars", 1, 20, 1)

with ui.card(full_screen=True):

    @render_ipycytoscape
    def network():
        widget = CytoscapeWidget(G)
        widget.set_style(STYLE)
        widget.set_layout(name="cose")  # computed once, from the full graph
        return widget

    @reactive.effect
    def _():
        # Hiding elements (not removing them) keeps every node's position, so
        # raising the slider back down instantly restores the full layout
        shown = {n for n in G if G.nodes[n]["degree"] >= input.min_degree()}
        for node in network.widget.graph.nodes:
            node.classes = "" if node.data["id"] in shown else "hidden"
        for edge in network.widget.graph.edges:
            s, t = edge.data["source"], edge.data["target"]
            edge.classes = "" if s in shown and t in shown else "hidden"

Removing nodes instead (remove_node_by_id()) is a structural edit that doesn’t preserve positions; prefer hiding for anything you expect the user to toggle back and forth.

Accessor reference

accessor returns before any interaction across re-render default rate policy
clicked_node() the clicked node’s cytoscape ele.json() dict (["data"] holds its data, including "id") None kept none
clicked_edge() the clicked edge’s ele.json() dict (["data"] has "id", "source", "target") None kept none
selected_nodes() the selected nodes’ data dicts, in graph order [] re-seeded debounce (0.25s)
selected_edges() the selected edges’ data dicts, in graph order [] re-seeded debounce (0.25s)

All four attach the moment the graph renders, so an interaction is never lost to timing. clicked_node()/ clicked_edge() keep their payload across a re-render until the user clicks the new graph – node ids from networkx are always strings, but edge ids are fresh UUIDs every render, so don’t persist a retained edge id across renders. selected_nodes()/selected_edges() instead re-seed from the new graph on every render, so they always describe what’s currently selected.

If you register your own widget.on(...) callbacks for other event types (mouseover, tap, etc.), do it inside the render function before returning the widget. A handler registered later, e.g. from a @reactive.effect, can be silently dropped.

clicked_edge()

import networkx as nx
from ipycytoscape import CytoscapeWidget
from shiny.express import render, ui
from shinywidgets import render_ipycytoscape

# A small corner of the Les Miserables co-appearance graph, with fixed
# positions so every edge lands in a predictable spot
G = (
    nx.les_miserables_graph()
    .subgraph(["Valjean", "Cosette", "Javert", "Marius"])
    .copy()
)
POSITIONS = {
    "Valjean": (200, 150),
    "Cosette": (400, 150),
    "Javert": (200, 300),
    "Marius": (400, 300),
}

STYLE = [
    {"selector": "node", "style": {"label": "data(id)"}},
    {"selector": "edge", "style": {"width": "mapData(weight, 1, 31, 1, 10)"}},
]

ui.page_opts(title="clicked_edge()", fillable=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_ipycytoscape
        def network():
            widget = CytoscapeWidget(G)
            widget.set_style(STYLE)
            for node in widget.graph.nodes:
                node.position = {
                    "x": POSITIONS[node.data["id"]][0],
                    "y": POSITIONS[node.data["id"]][1],
                }
            widget.set_layout(name="preset", fit=True, padding=40)
            return widget

    with ui.card():
        ui.card_header("Clicked tie")

        @render.ui
        def detail():
            clicked = network.clicked_edge()
            if clicked is None:
                return ui.p("Click an edge to see the shared scene count.")
            d = clicked["data"]
            return ui.p(f"{d['source']} and {d['target']} share {d['weight']} scenes.")

selected_nodes() and selected_edges()

Shown above, in Reacting to interaction. clicked_node() only reports single clicks; these cover the rest of ipycytoscape’s selection model – shift-drag box selection and multi-select – as a one-line read of the current selection, with no need to loop over the graph’s children yourself.

Don’t try to set node.selected from Python to drive selection – it toggles the node’s selectability instead. Use classes to highlight from Python instead, as in Reacting to interaction above.

Tuning accessors

Reading on demand

Because every accessor is already live and recording interactions the moment the graph renders, reading one for the first time inside a button handler or download handler works – there’s no need to display it reactively first to “warm it up”. A handler that only runs when the user asks for it still sees the latest selection:

import io

import networkx as nx
from ipycytoscape import CytoscapeWidget
from shiny.express import render, ui
from shinywidgets import render_ipycytoscape

G = nx.les_miserables_graph()
STYLE = [{"selector": "node:selected", "style": {"background-color": "#e15759"}}]

ui.page_opts(title="Read on demand", fillable=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):
        ui.card_header("Select a group, then export it -- no need to display it first")

        @render_ipycytoscape
        def network():
            widget = CytoscapeWidget(
                G, auto_unselectify=False, box_selection_enabled=True
            )
            widget.set_style(STYLE)
            widget.set_layout(name="cose")
            for node in widget.graph.nodes:
                node.selectable = True
            return widget

    with ui.card():
        ui.card_header("Export")
        ui.p("Nothing on this page reads selected_nodes() until you click Download.")

        @render.download_button(
            filename="selection.csv", label="Download selected characters"
        )
        def export():
            # Read on demand: no warm-up, no earlier display of this value --
            # selected_nodes() already has the latest selection the moment
            # the handler runs.
            rows = ["id"] + [d["id"] for d in network.selected_nodes()]
            yield io.BytesIO("\n".join(rows).encode()).getvalue()

Other traits worth reading

A couple of other traits sync from the browser but aren’t worth an accessor of their own: each node’s grabbed trait is True while the user is actively dragging it, and removed tracks structural edits. Read either with reactive_read(node, "grabbed") on a node in .widget.graph.nodes. Node position does not sync back (see Gotchas), so there’s no way to read a user’s manual drag target from Python.

For box-selection under heavier selection churn than this guide’s examples, the accessors’ own implementation is the pattern to copy: one node.observe(callback, "selected") per node, folded into a single reactive.value.

Rate limiting

render_ipycytoscape’s rate_policy/rate_delay kwargs cover reactive_read() on the top-level CytoscapeWidget and the graph’s child Node/Edge widgets – the ones that actually own selected and grabbed. They also override selected_nodes()/selected_edges()’s own debounce default (0.25s); clicked_node()/clicked_edge() aren’t rate-limited (every click is discrete and immediate, so there’s nothing to smooth out). One limitation worth knowing: nodes or edges added to the graph after a render aren’t covered until the next render.

.read()

Each accessor can also be read by name, network.read("clicked_node"), which is useful for code that reads accessors generically.

Large data

ipycytoscape doesn’t have a large-data mode: every node and edge is its own ipywidget, so render time scales with element count – comfortable into the low thousands of nodes, slow well past that. For graphs in the tens of thousands of nodes or more, reach for ipysigma instead, which draws with the GPU (WebGL) rather than one widget per element – the “draw it with the GPU in the browser” approach in Large data & performance’s three approaches.

Layout and sizing

render_ipycytoscape’s height/fill/fillable kwargs (and output_widget()’s) work the way every shinywidgets renderer’s do: the graph fills its card or parent container unless you give it an explicit height, and it tracks sidebar collapses, full-screen toggles, and window resizes. A few things specific to this widget:

  • Prefer the decorator’s or output_widget()’s height= over widget.layout.height: the latter sets the ipywidgets Layout trait directly, and the graph’s internal layout algorithm can run before that CSS applies, clipping the result to the default 400px rather than your requested height.
  • The graph does not re-fit itself on a container resize; pan and zoom are preserved through resizes exactly as they are through in-place updates (see above), which means part of the graph can end up outside the visible area after a big resize. Call widget.relayout() (re-runs the layout with a fresh fit) if you want to recover from that.
  • output_widget(height="auto") (or "fit-content") keeps ipycytoscape’s intrinsic 400px default instead of collapsing to 0px.

Gotchas

  • Node positions, pan, and zoom don’t sync from the browser back to Python. You can’t persist a user’s manual drag or read the current viewport; setting a node’s position from Python does still move it.
  • Setting CytoscapeWidget.zoom from Python has no effect in the browser – there’s no way to drive the viewport’s zoom level from Python. Restyle individual nodes and edges instead (position, classes, and style all work).
  • An invalid event name passed to widget.on() corrupts the widget’s callback registry, and every later .on() call then raises. Only use names from ipycytoscape.MONITORED_USER_INTERACTIONS (there’s no dblclick, for instance), and validate the name at import time if you’re taking it from user input.

Learn more