Static SVG Graph Diagrams for Technical Documentation
Documentation for a graph library has to show topology: which nodes connect, and in which direction messages flow. For a diagram with a handful of nodes you do not need a JavaScript library. SVG can draw it, and HTML details/summary can fold it away. The catch is that not every platform accepts inline markup.
This page is about node-edge diagrams. For diagrams of tensor shapes, see interactive tensor-shape diagrams. Python examples were tested with TGraphX 1.5.1.
Design goals
A good static graph diagram:
- renders without JavaScript;
- has an accessible name and description;
- is self-contained, so it can be copied or saved as one file;
- matches the code: arrows point the way messages travel.
For the last point, state the convention. In TGraphX, row 0 of edge_index is the source, row 1 is the destination, and messages travel from source to destination (also the PyTorch Geometric default).
Libraries such as D3.js or Cytoscape.js earn their weight when readers need to pan, zoom or hover over a larger graph. A five-node explanation does not need them.
A hand-written node-edge diagram
This example has five nodes and the edges n0→n1, n1→n2, n0→n3, n3→n2 and n2→n4. It is drawn from the point of view of n2: one message-passing layer brings it information from n1 and n3, a second layer brings in n0, and n4 is downstream of n2.
<figure>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 420 340" width="420" height="340"
style="max-width:100%;height:auto" role="img" aria-labelledby="mp-title mp-desc">
<title id="mp-title">Message passing into node n2</title>
<desc id="mp-desc">Directed edges n0 to n1, n1 to n2, n0 to n3, n3 to n2, and n2 to n4.
Node n2 receives from n1 and n3. Node n0 is two hops from n2.
Node n4 receives from n2.</desc>
<defs>
<marker id="mp-arrow" viewBox="0 0 10 10" refX="10" refY="5"
markerWidth="6" markerHeight="6" orient="auto">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#555"/>
</marker>
</defs>
<rect width="420" height="340" fill="#fff"/>
<!-- Edges: each line starts and ends on a circle boundary, not at a centre -->
<g stroke="#555" stroke-width="2" marker-end="url(#mp-arrow)">
<line x1="82" y1="60" x2="187" y2="60"/> <!-- n0 to n1 -->
<line x1="228.1" y1="72.5" x2="321.1" y2="136.9"/> <!-- n1 to n2 -->
<line x1="60" y1="82" x2="60" y2="177"/> <!-- n0 to n3 -->
<line x1="81.7" y1="196.1" x2="317.4" y2="154"/> <!-- n3 to n2 -->
<line x1="340" y1="172" x2="340" y2="237"/> <!-- n2 to n4 -->
</g>
<!-- Nodes: border style repeats what the fill colour says -->
<circle cx="60" cy="60" r="22" fill="#d0e8ff" stroke="#1f5fa8" stroke-width="2"
stroke-dasharray="6 4"/>
<circle cx="210" cy="60" r="22" fill="#d0e8ff" stroke="#1f5fa8" stroke-width="2"/>
<circle cx="60" cy="200" r="22" fill="#d0e8ff" stroke="#1f5fa8" stroke-width="2"/>
<circle cx="340" cy="150" r="22" fill="#ffe0b2" stroke="#a63c00" stroke-width="4"/>
<circle cx="340" cy="260" r="22" fill="#c8e6c9" stroke="#2e7d32" stroke-width="2"
stroke-dasharray="2 3"/>
<g font-family="monospace" font-size="14" text-anchor="middle" fill="#111">
<text x="60" y="65">n0</text>
<text x="210" y="65">n1</text>
<text x="60" y="205">n3</text>
<text x="340" y="155">n2</text>
<text x="340" y="265">n4</text>
</g>
<!-- Legend, in its own band below the graph -->
<g font-family="sans-serif" font-size="12" fill="#333">
<circle cx="20" cy="305" r="7" fill="#ffe0b2" stroke="#a63c00" stroke-width="3"/>
<text x="34" y="309">target (thick)</text>
<circle cx="215" cy="305" r="7" fill="#d0e8ff" stroke="#1f5fa8" stroke-width="2"/>
<text x="229" y="309">1 hop (solid)</text>
<circle cx="20" cy="326" r="7" fill="#d0e8ff" stroke="#1f5fa8" stroke-width="2"
stroke-dasharray="6 4"/>
<text x="34" y="330">2 hops (dashed)</text>
<circle cx="215" cy="326" r="7" fill="#c8e6c9" stroke="#2e7d32" stroke-width="2"
stroke-dasharray="2 3"/>
<text x="229" y="330">downstream (dotted)</text>
</g>
</svg>
</figure>
Five details are easy to get wrong:
- Trim the lines. If a line runs to the target's centre and the node is painted on top, the arrowhead disappears under the circle.
- Make ids unique. Ids are shared by every inline SVG on a page, so two markers both called
arrowcollide. - Set
viewBox. It lets the drawing scale down on narrow screens. - Paint a background. Dark text on a transparent SVG becomes hard to read on a dark page.
- Wrap it for Markdown. Inside a Markdown file, put inline SVG in a block element such as
<figure>or<div>and leave no blank lines in it. Otherwise the parser can cut the drawing into paragraphs, and readers see stray label text instead of a diagram. To save a separate.svgfile, copy the<svg>element without the wrapper.
Generate the SVG from edge_index
Hand-placed coordinates drift when the graph changes. A short function keeps the drawing tied to the same tensor your example code uses. You still choose the node positions.
import math
import xml.etree.ElementTree as ET
from html import escape
from pathlib import Path
import torch
import tgraphx as tgx
edge_index = torch.tensor([[0, 1, 0, 3, 2], # row 0: source
[1, 2, 3, 2, 4]]) # row 1: destination
graph = tgx.Graph(node_features=torch.zeros(5, 1), edge_index=edge_index) # checks the ids
positions = [(60, 60), (210, 60), (340, 150), (60, 200), (340, 260)]
RADIUS = 22
def distance_to_segment(p, a, b):
"""Shortest distance from point p to the straight line segment a-b."""
(px, py), (ax, ay), (bx, by) = p, a, b
dx, dy = bx - ax, by - ay
t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy)))
return math.dist(p, (ax + t * dx, ay + t * dy))
def graph_to_svg(edge_index, positions, *, uid, title, width=420, height=300):
pairs = edge_index.t().tolist()
desc = "Directed edges: " + ", ".join(f"n{s} to n{d}" for s, d in pairs)
out = [
f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" '
f'width="{width}" height="{height}" style="max-width:100%;height:auto" '
f'role="img" aria-labelledby="{uid}-title {uid}-desc">',
f'<title id="{uid}-title">{escape(title)}</title>',
f'<desc id="{uid}-desc">{escape(desc)}</desc>',
f'<defs><marker id="{uid}-arrow" viewBox="0 0 10 10" refX="10" refY="5" '
f'markerWidth="6" markerHeight="6" orient="auto">'
f'<path d="M0 0L10 5L0 10z" fill="#555"/></marker></defs>',
f'<rect width="{width}" height="{height}" fill="#fff"/>',
]
for src, dst in pairs:
(x1, y1), (x2, y2) = positions[src], positions[dst]
length = math.dist(positions[src], positions[dst])
if length < 2 * RADIUS + 13: # 1 px gap plus a 12 px arrowhead
raise ValueError(f"edge {src}->{dst}: self-loop, or no room for the arrow")
for i, p in enumerate(positions):
if i not in (src, dst) and distance_to_segment(p, positions[src], positions[dst]) <= RADIUS:
raise ValueError(f"edge {src}->{dst} would be hidden behind node n{i}")
ux, uy = (x2 - x1) / length, (y2 - y1) / length
out.append(
f'<line x1="{x1 + ux * RADIUS:.1f}" y1="{y1 + uy * RADIUS:.1f}" '
f'x2="{x2 - ux * (RADIUS + 1):.1f}" y2="{y2 - uy * (RADIUS + 1):.1f}" '
f'stroke="#555" stroke-width="2" marker-end="url(#{uid}-arrow)"/>'
)
for i, (x, y) in enumerate(positions):
out.append(f'<circle cx="{x}" cy="{y}" r="{RADIUS}" fill="#d0e8ff" '
f'stroke="#1f5fa8" stroke-width="2"/>')
out.append(f'<text x="{x}" y="{y + 5}" text-anchor="middle" '
f'font-family="monospace" font-size="14" fill="#111">n{i}</text>')
out.append("</svg>")
return "\n".join(out)
assert len(positions) == graph.num_nodes
svg = graph_to_svg(edge_index, positions, uid="gen", title="Five-node directed graph")
Path("message_passing.svg").write_text(svg, encoding="utf-8")
Because the output is XML, you can test the diagram like any other build artifact, for example in the documentation's CI job:
ns = {"svg": "http://www.w3.org/2000/svg"}
root = ET.fromstring(svg) # raises if the markup is not well formed
assert root.get("role") == "img"
assert root.find("svg:title", ns) is not None
lines = root.findall("svg:line", ns)
assert len(lines) == graph.num_edges
assert len(root.findall("svg:circle", ns)) == graph.num_nodes
def nearest_node(point):
return min(range(len(positions)), key=lambda i: math.dist(point, positions[i]))
# one line per edge, in edge_index order, drawn from the source to the destination
for line, (src, dst) in zip(lines, edge_index.t().tolist()):
start = (float(line.get("x1")), float(line.get("y1")))
end = (float(line.get("x2")), float(line.get("y2")))
assert (nearest_node(start), nearest_node(end)) == (src, dst) # connectivity and direction
assert line.get("marker-end") == "url(#gen-arrow)" # arrowhead at the destination
for point in (start, end): # not hidden underneath a node
assert min(math.dist(point, p) for p in positions) >= RADIUS - 0.1
The function is deliberately small. It draws straight lines, so a pair of opposite edges (u→v and v→u) would overlap, it rejects self-loops and edges too short to hold an arrowhead, and it does no layout. An edge passing behind a third node would be hidden there and could read as two edges, so the function raises instead; move one of the nodes. Its output has no blank lines, but if you paste it into a Markdown page, still add the <figure> wrapper. For larger graphs, compute positions with a layout tool (for example NetworkX's layout functions, scaled to pixels) or render DOT files with Graphviz at build time.
A GraphBatch diagram behind details/summary
A GraphBatch merges several graphs into one disconnected graph and shifts each graph's node ids by the number of nodes before it. Check the numbers you are about to draw:
def toy_graph(num_nodes, num_edges):
return tgx.Graph(node_features=torch.zeros(num_nodes, 1),
edge_index=torch.randint(0, num_nodes, (2, num_edges)))
g1, g2, g3 = toy_graph(4, 5), toy_graph(3, 4), toy_graph(5, 6)
batch = tgx.GraphBatch([g1, g2, g3])
assert batch.node_features.shape[0] == 12 and batch.edge_index.shape[1] == 15
assert batch.batch.tolist() == [0] * 4 + [1] * 3 + [2] * 5
assert torch.equal(batch.edge_index[:, 5:9], g2.edge_index + 4) # after g1's 4 nodes
assert torch.equal(batch.edge_index[:, 9:], g3.edge_index + 7) # after 4 + 3 nodes
A diagram that interrupts the reading flow can go inside details. Whether you want blank lines there depends on the content:
- Inline SVG or other raw HTML, as below: the same rule applies, no blank lines between
<details>and</details>. - A Markdown image or fenced block on GitHub: leave a blank line after
</summary>and another before</details>. Without the one after</summary>, readers see the literalor backticks.
Python-Markdown, and so MkDocs, leaves a Markdown image inside details as literal text by default. Enable the md_in_html extension and write <details markdown="1">, or use an <img> tag and check that its relative path still resolves on the built site.
<details>
<summary><strong>GraphBatch diagram</strong>: three graphs become one</summary>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 160" width="480" height="160"
style="max-width:100%;height:auto" role="img" aria-labelledby="gb-title gb-desc">
<title id="gb-title">GraphBatch of three graphs</title>
<desc id="gb-desc">Graphs with 4, 3 and 5 nodes and 5, 4 and 6 edges become one graph
with 12 nodes and 15 edges. Node ids are shifted by 0, 4 and 7.</desc>
<rect width="480" height="160" fill="#fff"/>
<g fill="#e8f4fd" stroke="#1f5fa8" stroke-width="1.5">
<rect x="10" y="20" width="100" height="80" rx="6"/>
<rect x="120" y="20" width="100" height="80" rx="6"/>
<rect x="230" y="20" width="100" height="80" rx="6"/>
</g>
<rect x="370" y="10" width="100" height="100" rx="6"
fill="#fff8e1" stroke="#a65c00" stroke-width="1.5"/>
<g font-family="sans-serif" font-size="11" text-anchor="middle" fill="#222">
<text x="60" y="42">g1</text>
<text x="60" y="60">4 nodes</text>
<text x="60" y="76">5 edges</text>
<text x="170" y="42">g2</text>
<text x="170" y="60">3 nodes</text>
<text x="170" y="76">4 edges</text>
<text x="280" y="42">g3</text>
<text x="280" y="60">5 nodes</text>
<text x="280" y="76">6 edges</text>
<text x="350" y="65" font-size="20">→</text>
<text x="420" y="32">GraphBatch</text>
<text x="420" y="52">12 nodes</text>
<text x="420" y="68">15 edges</text>
<text x="420" y="90">id shift 0, 4, 7</text>
<text x="240" y="140" font-family="monospace">tgx.GraphBatch([g1, g2, g3])</text>
</g>
</svg>
</details>
A row of node tensors in HTML and CSS
Where raw HTML and <style> are allowed, a flexbox row is a quick way to say that every node holds a tensor:
<style>
.node-row { display: flex; flex-wrap: wrap; gap: 6px; align-items: center;
font: 12px monospace; }
.node-box { padding: 10px 8px; border: 2px solid #1f5fa8; border-radius: 6px;
background: #d0e8ff; color: #111; text-align: center; }
</style>
<div class="node-row" role="img"
aria-label="N nodes, each holding a tensor of shape C by H by W">
<div class="node-box">n0<br>[C,H,W]</div>
<div class="node-box">n1<br>[C,H,W]</div>
<div class="node-box">n2<br>[C,H,W]</div>
<span>···</span>
<div class="node-box">n(N-1)<br>[C,H,W]</div>
</div>
<p><code>node_features</code>: shape [N, C, H, W]</p>
Where each form renders
| Target | What works | Watch out for |
|---|---|---|
| GitHub Markdown | A committed .svg file referenced as , details, Mermaid code blocks, ASCII art |
Inline <svg> is not drawn, and its title, description and label text can be left on the page; <style> is not applied and its CSS shows up as literal text |
| Hugo | Inline SVG or an image file | The default Goldmark renderer omits raw HTML unless markup.goldmark.renderer.unsafe is true; inline SVG also needs the wrapper and no blank lines |
| Jekyll, MkDocs | Inline SVG or an image file | Use the wrapper and no blank lines for inline SVG; theme CSS can restyle it |
| Sphinx (including on Read the Docs) | An image directive, or raw HTML | Raw HTML appears only in HTML output |
| Jupyter | IPython.display.SVG in a code cell |
Check how the exported notebook looks |
| LaTeX PDF builds | The same drawing converted to PDF | \includegraphics does not read SVG directly |
The wrapped examples on this page pass unchanged through a CommonMark parser (markdown-it) and through Python-Markdown, which MkDocs uses. Hugo and Jekyll themselves were not run: Hugo's Goldmark follows CommonMark, while Jekyll's default kramdown has its own HTML rules. Preview on your own target.
If you only need GitHub to show the topology, a Mermaid block avoids coordinates altogether:
flowchart LR
n0 --> n1 --> n2
n0 --> n3 --> n2
n2 --> n4
Checklist before publishing
- Inline SVG has
role="img", a<title>, and a<desc>when the structure matters. - An SVG used as an image has meaningful alt text where it is referenced; readers of the page do not get the file's internal title.
- Labels are real
<text>elements. - Colour is never the only carrier of meaning.
- Ids are unique across the page.
- Inline SVG in a Markdown file sits in a block wrapper such as
<figure>or<div>and has no blank lines. - The
summarytext says what is inside. - The diagram has been looked at on the real target, including a narrow screen and a dark theme.
Plain SVG and HTML need no build step and no CDN, which removes two things that can break documentation later. The price is that you manage layout yourself, so keep these diagrams small.