Skip to main content

Visualizing and exporting graphs

GraphViz DOT

from excel_grapher.grapher import to_graphviz

dot = to_graphviz(g, rankdir="LR")

Mermaid

from excel_grapher.grapher import to_mermaid

mm = to_mermaid(g, max_nodes=100)

Path-induced subgraphs for focused visualization

Use select_path_induced_subgraph(...) to isolate only nodes on directed dependency paths between source and target node sets, then pass the smaller graph to any exporter.

from excel_grapher.grapher import select_path_induced_subgraph, to_graphviz

focused = select_path_induced_subgraph(
    g,
    source_keys=["Sheet1!F1"],
    target_keys=["Sheet1!A1"],
    max_path_length=10,  # optional safety cutoff
    max_paths=1000,  # optional safety cutoff
)
dot = to_graphviz(focused, rankdir="LR")

The path search follows graph edge direction (A -> B means A depends on B), validates that all requested keys exist in the graph, and preserves edge guards/provenance in the returned induced subgraph.

Shortest-path subgraphs

Use select_shortest_path_subgraph(...) to keep only nodes on the hop-shortest paths between two cells. Search is directed by default. Pass directed=False when the cells are not ancestor/descendant — for example two inputs that share a consumer:

from excel_grapher.grapher import select_shortest_path_subgraph, to_graphviz

# A -> B and A -> C: no directed path B -> ... -> C
related = select_shortest_path_subgraph(
    g,
    source_key="Sheet1!B1",
    target_key="Sheet1!C1",
    directed=False,
)
dot = to_graphviz(related, rankdir="LR")

directed affects reachability only. The returned graph keeps original edge direction, guards, and provenance. If several paths share the shortest hop count, all of them are kept. A directed miss that still has an undirected path raises ValueError and mentions directed=False.

NetworkX (optional dependency)

from excel_grapher.grapher import to_networkx

G = to_networkx(g)

Sheet graph

to_sheet_graph(...) collapses a cell-level DependencyGraph (or any GraphReadView) to one node per worksheet. Cell edges between the same pair of sheets become a single directed edge whose label is the number of underlying cell edges. Intra-sheet edges are dropped unless you pass include_self_loops=True. Edge direction is unchanged: Calc -> Inputs means the Calc sheet depends on Inputs.

Pass the result to to_graphviz, to_mermaid, or to_networkx:

from excel_grapher.grapher import to_graphviz, to_mermaid, to_networkx, to_sheet_graph

sheets = to_sheet_graph(g)
dot = to_graphviz(sheets, rankdir="LR")
mm = to_mermaid(sheets)
nx_sheets = to_networkx(sheets)  # optional: nodes are sheet names, edges carry `weight`

Fully guarded between-sheet bundles render dashed (GraphViz style=dashed, Mermaid -.->), matching cell-level guarded edges.

Series graph

to_series_graph(...) collapses a cell-level DependencyGraph to one node per bound series. Cell edges between the same pair of series become a single directed edge whose label is the number of underlying cell edges. Intra-series edges are dropped unless you pass include_self_loops=True.

This quotient does not compute a schedule ranking. Contracting cells into series can invent cycles even when the cell graph is a DAG (the zipper case: debt depends on adjustment in the same period, adjustment depends on lagged debt). Statement-level visualization keeps those directions by residual distance; the series graph keeps the cycle.

Pass the result to to_graphviz, to_mermaid, or to_networkx. Occupancy can come from a SeriesCatalog, or from bindings plus a workbook path:

from excel_grapher.exporter import to_series_graph
from excel_grapher.grapher import to_graphviz, to_mermaid, to_networkx

series = to_series_graph(g, bindings, workbook="model.xlsx")
dot = to_graphviz(series, rankdir="LR")
mm = to_mermaid(series)
nx_series = to_networkx(series)  # optional: nodes are series ids, edges carry `weight`

When you already have a catalog (for example from statement visualization), collapse occupancy directly:

from excel_grapher.grapher import to_series_graph

series = to_series_graph(g, catalog)

Fully guarded between-series bundles render dashed, matching sheet-level and cell-level guarded edges.

Formula text on nodes

For to_graphviz, to_mermaid, and to_networkx, formula cells get a second line in the node label (cell address, then the formula). This is on by default (include_formula_on_nodes=True). Set include_formula_on_nodes=False to use only the cell address. Long formulas are truncated for display: max_formula_length defaults to 120 characters; use None for no limit. Truncated text ends with ....

Large graphs and module inference

For graphs that are too large for Graphviz or Mermaid, the current recommended workflow is:

Pass the graph (or a projection) directly. NetworkX is built only when the chosen layout or partition needs it (Louvain, spring, forceatlas2, Graphviz layouts). Custom layout plugins that ignore ctx.nx_graph do not force a conversion. to_networkx remains available when you want a NetworkX object.

The payload stores node coordinates, module/rank/depth metadata, and edge columns; the browser viewer consumes those directly.

from pathlib import Path

from excel_grapher.exporter import to_web_viz_payload
from excel_grapher.grapher import create_dependency_graph, write_web_viz_html

g = create_dependency_graph("model.xlsx", ["Sheet1!A1"], load_values=False)
payload = to_web_viz_payload(g)
write_web_viz_html(payload, Path("model.html"), data_mode="auto")

Lightweight visualization overview

Customizing visualization

The payload builder (to_web_viz_payload) and the viewer (write_web_viz_html) are powered by plugins. A single default plugin is provided for each, but you are encouraged to write your own. Configure to_web_viz_payload(...) via:

  • layout="...": layout plugin id (clustered_force default; see list_web_viz_layouts()).
  • layout_config={...}: plugin-specific optional config.
  • include_guarded_edges: include/exclude guarded edges in core/local edge export.
  • include_guarded_edges_for_partition: include/exclude guarded edges in module partitioning.
  • include_module_overlay: include partition overlay metadata and module color semantics.

Shared layout: clustered force

Both viewers (cells here, statements below) use one layout policy from excel_grapher.grapher.viz_layout (install the viz extra: pip install excel-grapher[viz]): a force layout grouped by the graph’s natural clusters (directed Louvain modules for cells, series for statements), computed in levels so large graphs stay tractable:

  1. Force layout on the graph of clusters, one node per cluster.
  2. Force layout of every node, anchored to its cluster’s position.
  3. For large graphs, a few global refinement ticks.

A weak vertical pull towards input depth (longest path from the inputs) keeps the input -> output direction readable: inputs sit at the top. rank_pull selects it: "between" clusters (default), "everywhere" (also weakly inside each cluster), or "none". With a pull, cluster centroids are also aligned on the horizontal axis, so clusters stack into one input -> output column (clustered_force_layout(..., align_clusters=False) turns that off).

from excel_grapher.exporter import to_web_viz_payload, list_web_viz_layouts
from excel_grapher.grapher import write_web_viz_html

payload = to_web_viz_payload(
    g,
    layout="clustered_force",  # default
    layout_config={"rank_pull": "between"},  # or "none" / "everywhere"
    include_module_overlay=True,  # include Louvain partition overlay
)
write_web_viz_html(payload, "model-web.html", data_mode="auto")

Viewer behavior follows three size tiers shared by both viewers (VIZ_TIER_SMALL_MAX, VIZ_TIER_MEDIUM_MAX; the HTML gets them injected with the force settings, so browser relayout matches the precomputed layout):

Size Precomputed layout Drawing Relayout in the browser
Small (≤ 2,000) exact repulsion labeled boxes (statements) / points (cells) whole graph, when Vertical pull or Cluster by changes
Medium (≤ 20,000) exact repulsion inside clusters boxes, labels depend on zoom the selected cluster or neighborhood
Large grid repulsion plus refinement opens on the cluster overview; click a cluster or zoom in for dots / points the selected cluster only

Size is node count for cells and statements plus twice the bundles for statements.

Interpret the cell viewer with this mental model:

  • Position: x/y - Louvain modules as regions, inputs pulled towards the top.
  • Color: node color maps to module_id (partition/community id). With no module overlay, all nodes are one module color.
  • Edges: overview prefers node-level local_edges; if unavailable, it falls back to module-centroid edges.
  • Label Module edges / Graph edges: reflects which edge set is currently drawn in overview.
  • Rank in tooltip is SCC-condensation rank metadata, not a drawing axis.

excel_grapher.exporter.to_web_viz_payload(...) includes the partition overlay by default and is the canonical payload entrypoint for this visualization workflow. Open the exported HTML directly in a browser. The interface supports panning, zooming, hover tooltips, and Relayout selection for untangling the neighborhood (or, on large graphs, the module) around a selected node.

Statement graph (series bindings)

Cell-level visualization does not scale to million-edge workbooks. When series bindings exist, build a statement graph: one node per formula-shape run, with instance edges deduplicated by access class and schedule distance. Instance partitions stay on the bundles as metadata. Ranks use the distance-zero residual (same legality test as inverted-tree scheduling), not Louvain modules. Positions come from the shared clustered force layout with series as clusters.

from pathlib import Path

from excel_grapher.exporter import to_semantic_viz_payload, write_semantic_viz_html
from excel_grapher.grapher import create_dependency_graph
from excel_grapher.series_bindings import load_series_bindings
from excel_grapher.series_bindings.workflow import all_series_targets

bindings = load_series_bindings("bindings.yaml")
g = create_dependency_graph(
    "model.xlsx", all_series_targets(bindings, workbook=Path("model.xlsx")), load_values=True
)
payload = to_semantic_viz_payload(
    g, bindings, workbook="model.xlsx", blank_ranges=["Lookup!A1:C3"], rank_pull="between"
)
write_semantic_viz_html(payload, Path("model-statements.html"))

CLI:

uv run excel-grapher bindings viz model.xlsx --bindings bindings.yaml --output model-statements.html
uv run excel-grapher bindings viz model.xlsx --bindings bindings --blank-ranges blank_ranges.py --output model-statements.html
uv run excel-grapher bindings viz model.xlsx --bindings bindings.yaml --rank-pull none --output model-statements.html

Cell-level to_web_viz_payload is unchanged and does not require bindings.

The HTML viewer always paints to a canvas and follows the size tiers above. Q-CRAFT-scale graphs (~715 statements / 5,725 bundles, the medium tier) draw labeled boxes and arrows; labels appear once zoomed in far enough to read. Large statement graphs (LIC-DSF is ~20k statements / 120k bundles) open on a cluster overview (one disc per series, sized by statement count, with aggregated edges); click a disc or zoom in to see its statements as dots and lines. Large catalogs uncheck Constants on first paint. An on-page legend documents access-class edge colors (identity blue, shift purple, affine green, gather / whole / dynamic / cross_partition amber), dashed lag vs solid contemporaneous stroke, guarded fade, and node fill for the current Color by mode (series hue by default, or a named role palette, or per-sheet hue with a visible mixed group when a statement spans worksheets). Cluster by (series by default, or role, sheet, none) draws one labeled hull per group; on small graphs changing it relayouts in the browser so each group gets its own region (none is a plain force with no hulls), and so does Vertical pull. On medium and large graphs both are precomputed (re-export with --rank-pull to change the pull) and Relayout untangles the selected node’s cluster (or its two-hop neighborhood when Cluster by is none). Click a node or edge to open the inspect panel: nodes list sampled member cells and instance-partition chips; edges list sampled canonical instance pairs. Reset restores the precomputed layout and the opening camera without changing direction filters. Inline HTML samples up to eight cell addresses per node and eight instance edges per bundle; payload.to_dict() and excel-grapher bindings viz --json keep the full lists. Each node includes shape_key and a labels object copied from the series binding (notes, sdmx_notes, compute_name, groups, measure concept id/name/description, axis_labels). Formula text is not stored on statement nodes; use series, statement, partition, or bundle drilldown for cell formulas and canonical instance edges.

from excel_grapher.exporter import (
    drilldown_bundle,
    drilldown_partition,
    drilldown_series,
    load_semantic_catalog,
    statement_graph_to_networkx,
    to_semantic_viz_payload,
)

view = load_semantic_catalog(g, bindings, workbook="model.xlsx")
payload = to_semantic_viz_payload(g, bindings, workbook="model.xlsx", view=view)
nx_statements = statement_graph_to_networkx(payload.graph)  # MultiDiGraph; no formulas
path = drilldown_series(view, g, "path")
formulas = [cell.formula for cell in path.cells]
nx_cells = path.to_networkx()  # MultiDiGraph of cells, with formula attributes
france = drilldown_partition(view, g, "debt", ("France",))
identity = drilldown_bundle(
    view, g, consumer_id="debt__1", producer_id="adjustment", access="identity", distance=0
)

drilldown_statement(view, g, "path__1") narrows that expansion to one shape run. drilldown_partition keeps one outer-key block. drilldown_bundle lists every canonical instance edge behind a compressed bundle. Drilldown edges keep series ids and add consumer_statement_id / producer_statement_id so they join to the statement graph. NetworkX statement edges are consumer -> producer (depends-on) and keep access, distance, affine coefficients, guarded, partition keys, and representative cells. Nodes carry a representative_cell rather than formula text. Multiple bundles between the same pair remain distinct multi-edges. excel_grapher.grapher.to_networkx rejects statement graphs and drilldowns; use statement_graph_to_networkx or SeriesDrilldown.to_networkx.

On the Q-CRAFT extraction-pipeline workbook (Teal-Insights/qcraft-extraction-pipeline, 260,027 bound cells / 489,651 graph edges), catalog analysis plus the statement quotient finished in about 16s and emitted 715 statements / 5,725 bundles (no unbound remainder). Workbooks that declare BLANK_RANGES (LIC-DSF) must pass the same list into catalog analysis; otherwise range walks fail-closed on those spacer cells.

Validation via calcChain.xml

You can validate the graph against Excel’s calcChain.xml:

from pathlib import Path

from excel_grapher.grapher import create_dependency_graph, validate_graph

g = create_dependency_graph("model.xlsx", ["Sheet1!A10"], load_values=False)
res = validate_graph(g, Path("model.xlsx"), scope={"Sheet1"})
print(res.is_valid, res.messages)

If xl/calcChain.xml is missing (common for generated files), validation returns is_valid=True with an informational message.