Skip to content

Drawing a graph

Two renderers, and the one you want depends on who is reading.

to_text(graph) prints the structure, every CPD row and the current beliefs. It needs nothing beyond the standard library, and it is usually the fastest way to see what state a graph is actually in.

from probability_flow import to_text
print(to_text(g))

render(graph) draws it. Causes sit above effects, observed variables are marked, and a gate is drawn as a switch wired into the edge it modulates rather than as an arrow of its own. It needs matplotlib, which is the library's only optional dependency:

pip install "probability-flow[viz]"
from probability_flow import render
render(g)                       # returns a matplotlib figure

Everything below is a keyword to render, and the defaults are the settled ones, so the shortest correct call is render(g). A few keywords also answer to a friendlier spelling, so gate reaches gate_glyph and colours reaches bar_colors, but you never need to know that. Whatever you can read off a table here, you can pass.

One thing to know before the tables make sense. A variable carrying virtual evidence is drawn as a badge on the node it is about rather than as a node of its own, so a document with 51 variables can draw 46 boxes. Counts below are variables unless they say otherwise.

Everything the renderer can draw, in one picture. The key is legend=True, which names only the marks this particular graph uses rather than all of them.

A causal graph of eleven claims about whether a package was stolen. The claim
under debate has a heavier border. Two claims join by green double lines into a
definition, which carries a circled conjunction sign. Edges are blue where they
support and red where they undercut. One edge carries a switch, drawn as a pole
with two throws labelled plus 0.4 and plus 4.8 bits, with a dashed purple arrow
from the claim that sets which throw is live. One variable has an amber border
because it was observed rather than inferred. Three claims carry evidence
badges, one reading up 1.9 bits, one down 1.6 bits, and one an empty ring for an
instrument that has not reported.

Layout

How nodes are placed and how edges get from one to another.

Keyword Default Selects
flow "down" "down" or "right"
layering "alap" "alap" packs toward effects, "asap" toward causes
routing "curve" "curve" or "direct"
curve 0.5 an upper bound on the pull of a curve
attach "auto" "auto", "face" always, "ray" never
bias 2.0 exponent on the across-flow fraction
wrap 1.55 target label width, inches
gap 0.26 minimum gap between boxes, inches
rank_gap 0.45 clear air between layers, inches
fontsize 9.0 points
min_fontsize 4.5 points below which labels truncate instead of shrinking
grow_figure True enlarge a caller's figure rather than shrink the drawing

Which way to lay a graph out

flow is a property of the graph rather than a preference, and two numbers decide it. Count the levels in the graph and the number of nodes on its busiest level. The layering stage produces the first and the ordering stage produces the second, and flow="right" simply swaps which of the two becomes the figure's width.

If there are at least as many levels as there are nodes on the busiest one, the graph is deep and narrow, it comes out tall under the default, and "right" fits a page better. If the busiest level is wider than the graph is deep, which an extremely wide fan-in is the clearest case of, the default already wins.

Graph Levels Busiest Fits a 16:9 page larger
the 11-variable worked example 3 3 "right", by 1.3x
a 21-variable argument 6 4 "right", by 1.2x
a 39-variable argument 7 5 "right", by 1.7x
a 36-variable argument 7 9 "down"
a 23-variable argument with a 10-parent node 5 10 "down"
the 51-variable worked example 6 13 "down"

Six graphs is a rule of thumb rather than a law, but the mechanism behind it is not a coincidence, and the two closest calls above are the two nearest the boundary.

The same graph both ways. Seven levels against five on the busiest one, so it is the deep-and-narrow case and "right" is the one that fits a wide page.

The example graph laid out top to bottom. It is tall and narrow, running to
seven levels with at most five claims side by side on any one of
them.

The same graph laid out left to right. The same eleven claims now run across
the page in seven columns, so the figure is wide and short rather than tall and
narrow.

The two you reach for next

wrap is the one worth knowing about. It sets how wide a label is allowed to get before it wraps, and because labels are propositions rather than variable names, it has more effect on a figure's shape than anything else here. Raising it makes boxes wider and shorter, which packs a deep graph into fewer levels of height. A 39-variable graph laid out sideways went from 17.9 inches wide to 21.6 and from 11.5 tall to 10.8 on wrap=2.1, which was the difference between fitting a slide and not.

When you pass your own axes

render(g, ax=...) draws into an axes you already have, which is how you put two graphs side by side. One thing is worth knowing before you do.

A graph has a size it wants, and render(g) on its own gives it exactly that. If the axes you pass is smaller, the figure is enlarged to fit rather than the drawing shrunk into it. A subplot's cell is a fixed fraction of its figure, so growing the figure leaves every sibling axes in proportion and the panels stay the same relative size.

That is the right way round because shrinking does not work. The layout is in inches and text is in points, and only one of those follows an axes, so a drawing squeezed into a small cell keeps full-size labels over quarter-size boxes. Scaling the type down to match looks faithful and is no better: the bar and the badge are geometry too, so they shrink with it, and every part of the drawing ends up illegible rather than one part being too big.

Pass grow_figure=False when the figure's size is yours and must not move. Then the type is scaled down to match the boxes, with min_fontsize as the floor and truncation past it, and a warning naming both sizes. That warning is worth reading rather than silencing: a graph that lays out at 19 inches tall does not become legible in a 7 inch panel. Render it on its own and place the image.

rank_gap is clear air between levels, and the default leaves less of it than a node box is tall, which keeps a deep graph compact. Raise it when you have turned annotations on and the numbers between two levels are colliding, which is the one case that reliably needs the room.

Edges

Keyword Default Selects
constitutive "double" double, triple, dotted, double-dotted
constitutive_colour "green" "green", "neutral", or any colour
weight_colour True colour a causal edge by its signed weight
weight_scale 4.0 bits at which the ramp saturates
ramp "coolwarm_r" reversed, so positive is blue and negative red
ramp_floor 0.62 cap on luminance
annotations False print each edge's weight beside it
bits_word "bits" "bits" or "b"

A constitutive edge says one proposition is part of what another means, rather than something that influences it. It is drawn as two fine strands close enough together to read as one line rather than as two, in green, which is the one hue the drawing does not otherwise spend. Shape and colour are separate keywords because they are separate questions, and either alone carries the meaning if the other is unavailable, which matters for a figure printed in grey.

Two claims and the definition they constitute, drawn three ways. The graph is small on purpose: the difference between these shapes is the gap between two strands, and on a whole-graph figure that gap is about a pixel.

Two claims joined to a definition by edges drawn as two fine green parallel
lines, close enough together to read as a single
line.

The same three claims, with the constitutive edges drawn as a single line of
fine round dots rather than as a pair of solid
strands.

The same three claims again, with the constitutive edges drawn as three
parallel strands, which at this size begin to merge into one thick
band.

The weight ramp is over the sign rather than the magnitude, because a weight is a conditional log-odds ratio with a meaningful zero, and a ramp over the absolute value would throw away the one thing colour is best placed to show.

Where the ramp should saturate

weight_scale is the number of bits at which an edge reaches full colour. Everything past it draws the same, so the question is what the strongest edge in your graph is actually worth. Generated graphs rarely exceed 4 bits, which is why 4 is the default, but a hand-authored argument readily goes further. A gated edge at 8.8 bits is not unusual, and at the default that edge and every 4-bit edge beside it draw the same blue.

Raise it when you have authored weights beyond 4 bits and want them to stand apart. Lower it when every edge in a graph is weak and they are all washing out together. The cost of raising it is that the middle of the range stops discriminating, so one scale across a set of figures is worth more than a per-figure best fit if the figures will be compared.

Whether annotations survive a big graph

They get easier on bigger graphs, not harder, which is the opposite of what you would expect. A figure grows faster than its count of weighted edges, so label density falls as graphs grow. Measured as labels per 100 square inches of figure:

Graph Labels Density
a 21-variable argument 20 24.5
a 39-variable argument 17 7.6
the 51-variable worked example 26 6.9

So node count is the wrong thing to worry about. What crowds a drawing is a small graph with densely weighted edges, and the densest case measured is the smallest graph of the three.

Off and on, same graph. Note that the gate labels its two throws either way, because a switch has to say what it is switching between.

The example graph with no edge annotations. Only the gate carries numbers,
labelling its two throws plus 0.4 and plus 4.8 bits.

The same graph with annotations turned on. Every edge that carries a weight
now prints it beside the line, each number drawn in the colour of its own edge,
so a supporting edge and its number are both blue and an undercutting one and
its number are both red.

Two things keep the clutter down without you asking. An edge with no weight never collects an empty label, so constitutive edges and table-CPD edges are skipped, and each label takes the colour of its own edge, which is what attributes a number to a line once there are more than a few. One consequence worth knowing before you reach for the keyword: on a graph whose nodes are all logical, turning annotations on changes nothing at all, because a logical CPD has no per-edge weight to print.

Gates

A gate replaces the weight of the edge it modulates, so it is a multiplexer rather than an attenuator. It is drawn as a switch on that edge, and a gate source that carries no weight of its own gets no arrow to the child at all.

Keyword Default Selects
gate_glyph "switch" "switch" pole and two throws, "valve", "tee", "tap"
gate_label "becomes" "becomes", "switch", "delta", "none"
switch_angle 15.0 degrees between the two throws
switch_arm 0.35 pole to contact, inches, a fixed size
switch_bias 0.5 share of the leftover run given to the lead-in
switch_track True an arc the blade can rest anywhere on
hide_inert_gate_edge True hide the arrow for a gate that carries no weight

Which glyph, and when the label matters

The default "switch" is the only glyph that shows both weights. It draws a pole with two throws, labels each throw with its own number, and colours each by its own weight on the same ramp as every other edge. The blade rests on an arc between them and its angle is the credence, because a gate is not all or nothing and the mixture is linear in the gate's probability. The picture and the arithmetic are the same interpolation.

That makes the switch the right glyph for a gate whose magnitude matters, in either direction. A gate that reverses an edge's sign is the case it handles best of all, because the reversal draws itself: one throw comes out blue and the other red, and no wording can compete with seeing the two side by side.

"valve", "tee" and "tap" are single marks on the edge with a text label instead. Reach for one when the gate is incidental to what the figure is about and you want it noted rather than explained.

gate_label only applies to those three. Under the default switch it has no effect, because each throw already carries its own number, which is strictly more than any of these can say:

gate_label Prints
"becomes" ⇒ +4.6 bits, the weight the gate installs
"switch" +1.0 → +4.8 bits, both weights
"delta" +3.8 bits, the change
"none" nothing

"switch" is the one to pass if you have moved off the default glyph and the before matters as much as the after. "becomes" is enough when it does not.

Nodes and belief

Keyword Default Selects
show_prob "bar" "bar", "number", "none"
bar_colors "grey" "grey", "ramp", "valence", "tab10"
badge "chip" "chip", "arrowtag", "dial"
idle_badge "ring" "ring", "number", "off"
badge_outcome False name the outcome on the chip as well
family True mark a node that is not plainly independent
hypothesis "thick" "thick", "blue", "none"
ghost_alpha 0.45 how far an unrevealed node fades
frontier False the amber ring
legend False

A node that combines its parents additively carries no family mark, because nearly every node does and a bubble on all of them is clutter that says nothing. The coloured edges running into an additive node already imply it. Only a node that combines its parents some other way is genuinely ambiguous, so a conjunctive one gets a circled and, a disjunctive one a circled or, and a counted one its own threshold. The graph still knows an additive node is additive. What a node is and what gets drawn are separate questions, and only the second one this keyword touches.

A badge is virtual evidence folded onto the node it is about. Node family and definitional-ness are separate channels, because they are independent axes: a definition is a logical And or Or, an ordinary node is noisy or independent, and a node can be both.

Choosing a badge

"chip" prints the number in an outlined box and is the default because the number is the point. "arrowtag" is the same content in a filled arrow pointing into the node, which is louder and worth it when a figure has one or two instruments you want noticed. "dial" gives up the number for a small gauge whose arc is the magnitude, and it is 0.30 inches wide against the chip's 0.75.

Reach for the dial when badges are crowding each other rather than when the figure is large. It does not change the figure's size, because badges hang off their nodes and do not drive the layout. What it buys is a much smaller mark on a graph where most nodes carry an instrument, at the cost of being able to read the strength exactly.

What bar_colors="valence" is for

It paints the bar in the ramp's own endpoint colours, so a node reads true or false at a glance from across a room. That is its use, and it is a narrow one. It is not the default because a bar and an edge encode different quantities. An edge's blue is a weight in bits and a bar's blue would be a belief, and one hue across both invites a comparison that is not valid. It also misleads in a specific way worth knowing: a node at 0.80 false paints a wide red bar that reads like strong negative evidence, when all it means is that the node is probably false.

"ramp" is the middle option, tinting the true slice by the node's own log-odds so an undecided node comes out grey and only a confident one takes on hue. "grey" stays the default because two greys read as one filled quantity, which is what a probability is.

Whether to turn the legend on

Yes, for anyone who has not seen one of these drawings before. There are nine marks to learn and the legend names the ones your graph actually uses rather than all of them. It wraps to the width of the drawing rather than setting it, so the cost is vertical space at the bottom and nothing else.

Turn it off once a reader knows the language, or when a figure is one of a set and the legend would repeat on every one.

How big a graph can this draw

Bigger than you would expect. A 51-variable argument renders in about a fifth of a second, and every box in it stays legible.

Node count is the wrong measure. A figure's size is set by the busiest level, not by how many nodes there are in total. A 23-variable argument with a ten-parent node comes out 21 inches wide, while a 39-variable argument whose levels are narrow comes out 12.

What degrades first is not legibility but following one edge across the page. Boxes stay readable and the typical edge barely grows, but the longest edges grow with the drawing:

Variables Figure Longest edge Typical edge
11 6 x 6 in 2.5 in 2.4 in
21 8 x 10 in 5.0 in 2.5 in
39 12 x 19 in 8.6 in 3.6 in
36 18 x 11 in 11.6 in 2.4 in
51 29 x 13 in 10.5 in 3.4 in

The typical edge grows from 2.4 inches to 3.4 across that whole range. The longest one more than quadruples. So the practical limit is the page you are putting the figure on, and the thing to do about a graph that has outgrown it is to draw a part of it rather than to shrink the whole.