Skip to content

How to draw a graph

This guide shows you how to draw a node-link graph, react to a click on a node, highlight a path through it, and keep a graph with thousands of nodes readable. It assumes you have read the Quickstart.

Draw a graph

Save this as team.py. It is a complete app: five people, who works with whom, and a line of text that shows the person you click.

import indah

people = [
    {"id": "ana", "group": "Design"},
    {"id": "ben", "group": "Design"},
    {"id": "cho", "group": "Platform"},
    {"id": "dev", "group": "Platform"},
    {"id": "eli", "group": "Data"},
]
works_with = [("ana", "ben"), ("ben", "cho"), ("cho", "dev"), ("dev", "eli"), ("ana", "eli")]

selected = indah.Signal(None)

app = indah.Column(
    children=[
        indah.Graph(people, works_with, selected=selected, height=360, label="Who works with whom"),
        indah.Text(lambda: f"Selected {selected.value}" if selected.value else "Click a person"),
    ]
)

if __name__ == "__main__":
    indah.launch(indah.create_app(session=indah.Session(app)))

Run it with python team.py. Drag the canvas to pan, scroll to zoom, and click a person: the text under the graph shows who you clicked, and a click on empty canvas clears it.

group picks a colour and adds a legend. Positions are worked out in your browser and start clustered by group, so the same graph always lays out the same way.

Graph - A node-link graph: drag to pan, wheel to zoom, click a node to select it. Only the nodes nearest the middle are drawn in full; the rest are dots.
def graph_page(ctx: indah.Context) -> indah.Component:
    nodes, edges = _demo_graph()
    path = _longest_path(edges, "n0")
    selected = indah.Signal(None)
    hovered = indah.Signal(None)
    window = indah.Signal(120)
    trace = indah.Signal(False)
    return indah.Column(
        children=[
            indah.Graph(
                nodes,
                edges,
                selected=selected,
                hovered=hovered,
                focus_size=window,
                highlight=lambda: path if trace.value else None,
                height=420,
                label="A community graph of 900 nodes",
            ),
            indah.Slider(window, min=20, max=900, step=10, label="Nodes drawn in full"),
            indah.Switch(trace, label="Highlight the longest path from n0"),
            indah.Text(lambda: f"Selected {selected.value}" if selected.value else "Click a node"),
            indah.Text(lambda: f"Hovering {hovered.value}" if hovered.value else "Hover a node"),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/media/graph)

Select a node from Python

selected works both ways. Set it and the graph selects that node and centres on it:

selected.set("dev")

focus centres on a node without selecting it. Give it an id, or a signal that holds one.

Follow the pointer

Bind hovered and it holds the id of the node under the pointer, or None over none of them:

hovered = indah.Signal(None)
indah.Graph(people, works_with, hovered=hovered)
indah.Text(lambda: f"Hovering {hovered.value}" if hovered.value else "Hover a node")

It is one way: setting hovered from Python does not move the graph. With no hovered signal the graph sends nothing when the pointer moves.

Hover shares the /api/event rate limit with every click, slider and button, so the graph spends it sparingly. It posts only when the hovered node changes, and only after the pointer has rested for about 250 ms. Sweeping across a hundred nodes costs one event. At the worst, a pointer that settles on a new node every quarter of a second spends four events a second, which a hosted app on indah.Rate(per_second=5, burst=30) (see Gateways, limits and CSP) absorbs without starving other controls. If the server does answer 429, the graph drops that update without a message and the next change posts again.

Highlight a path

Give each edge an id, then name the nodes and edges to emphasise:

edges = [{"source": "ana", "target": "ben", "id": "e1"}, ...]
path = {"nodes": ["ana", "ben", "cho"], "edges": ["e1", "e2"]}
indah.Graph(people, edges, highlight=path)

Highlighted nodes and edges are always drawn in full, and everything else is dimmed. highlight can be a signal, so you can show a different path as your user moves through a list. An id that is not in the graph raises ValueError when you build the graph, not later in the browser.

Tip

Change nodes and edges together, inside indah.batch(...), when both are signals. Set one at a time, and an edge can briefly name a node that is not there yet.

Keep a big graph readable

A graph with thousands of labelled nodes is a hairball. Graph draws only the focus_size nodes nearest the middle of the canvas in full (default 300), with their labels and the edges between them. Every other node is a small dot, so you still see the shape of the whole graph. Pan, and the detail follows you. Click a dot and it is selected, centred and drawn in full, along with its nearest neighbours.

  • Raise or lower focus_size (1 to 5,000) to trade detail for speed. It can be a signal, so a slider can drive it.
  • A graph holds at most max_nodes nodes (default 10,000, up to 20,000) and three times as many edges. Past that, sample the graph before you hand it over.
  • Above 8,000 nodes the nodes start clustered by group and are not relaxed further.

Show state without moving anything

A graph that changes over time (a year, a run) often needs to say "this ended", "this is new" and "this is not there yet" without anything jumping. Give a node opacity, a ring or label_style="strike", and an edge dash, opacity or width. Styles draw the same far from the centre: a dashed edge is still dashed, and a ringed dot keeps its ring. Add layout="stable" and the layout depends on ids and edges only, so changing a style, a group or the order of the nodes never moves a node.

nodes = [{"id": "a", "ring": True}, {"id": "b", "opacity": 0.4, "label_style": "strike"}]
edges = [{"source": "a", "target": "b", "dash": True}]
indah.Graph(nodes, edges, layout="stable")

Draw a DAG

For a pipeline or a lineage, pass directed=True for an arrowhead at each edge's target and layout="layered" to lay it out top to bottom with no simulation. A node can also take a shape ("circle", "square" or "diamond") and dash (a dashed outline with a faint fill), so a state such as "not built yet" does not rest on colour alone.

nodes = [
    {"id": "raw", "shape": "square"},
    "clean",
    {"id": "report", "shape": "diamond", "dash": True},
]
indah.Graph(nodes, [("raw", "clean"), ("clean", "report")], layout="layered", directed=True)

A node sits one layer below its deepest parent. A cycle is broken at its first node in list order, and each layer is ordered to cut crossings. A node far outside the focus window is still a dot.

Graph DAG: arrows, shapes and layers - directed=True draws arrowheads, a node takes shape and a dashed outline, and layout="layered" places a DAG top to bottom with no simulation.
def graph_dag_page(ctx: indah.Context) -> indah.Component:
    nodes = []
    for name, shape, dashed in _DAG:
        node: dict = {"id": name, "label": name, "size": 9}
        if shape:
            node["shape"] = shape
        if dashed:
            node["dash"] = True  # not built yet
        nodes.append(node)
    return indah.Graph(
        nodes,
        _DAG_EDGES,
        layout="layered",
        directed=True,
        height=380,
        legend=False,
        label="A data pipeline",
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/media/graph-dag)

Play a graph through frames

When a graph changes by moments (years, checkpoints), send the base graph once and a few style patches per frame. A frame is the base plus only its own patches, so any frame can be shown directly. Edges need an id to be patched; hide takes node or edge ids and draws them at opacity 0 in their place.

graph = indah.Graph(
    nodes,
    edges,
    layout="stable",
    frames=[{}, {"nodes": {"a": {"ring": True}}, "edges": {"ab": {"dash": True}}}],
    frame=frame,  # optional Signal[int], two way
)
indah.Timeline(year, [2000, 2001], link=graph)

The browser applies a frame itself. Timeline(link=graph) steps the frames locally while it plays, so playing sends no events; the index is reported once on a pause, at the end or on a manual step. There can be at most 400 frames and 60,000 patch entries in all, and unknown ids raise ValueError.

Keep positions when the graph changes

By default a replaced graph is laid out afresh. Pass update="keep" and every id the graph already had stays exactly where it was (and the viewer's pan and zoom are kept); only new ids are placed, near the neighbours they are linked to. Add transition_ms (0 to 2,000) to fade new nodes in and ease opacity and edge width changes; it does nothing under prefers-reduced-motion.

indah.Graph(lambda: grown.value[0], lambda: grown.value[1], update="keep", transition_ms=300)

Use the keyboard

Press Tab to focus the graph. Arrow keys pan, + and - zoom, and Escape clears the selection.

Reference

Argument Meaning
nodes ids, or dicts with id and optional label, group, size, color, x, y, ring, opacity, label_style, shape, dash
edges (source, target) pairs, or dicts with source, target and optional id, label, color, dash, opacity, width
selected a Signal[str \| None], two-way
hovered a Signal[str \| None], one-way: the node under the pointer (debounced about 250 ms)
focus a node id, signal or callable: centre on it
focus_size nodes drawn in full (default 300, at most 5,000); may be a signal
highlight {"nodes": [...], "edges": [...]}; may be a signal
layout "auto" (default), "stable" (seeded from ids and edges only), "layered" (a DAG, top to bottom) or "given", which needs x and y on every node
directed draw an arrowhead at each edge's target (default False)
layout "auto" (default), "stable" (seeded from ids and edges only) or "given", which needs x and y on every node
frames a list of {"nodes": {id: style}, "edges": {id: style}, "hide": [ids]} patches, one per frame
frame a Signal[int], two way: the frame on show
update "relayout" (default) or "keep": a replaced graph keeps the position of every id it already had
transition_ms 0 (default) to 2,000: ease opacity and edge width changes, fade new nodes in
height pixels, or "fill"
legend show the group colours (default True)
max_nodes most nodes allowed (default 10,000; ceiling 20,000)
label the name a screen reader announces

A duplicate id, an edge to a node that is not in the graph, or too many nodes raises ValueError when you build the Graph. The decision record is ADR-0048.