# How to Draw a Causal DAG in Python with NetworkX

> Draw a causal DAG in Python with networkx.DiGraph and draw_networkx, find backdoor paths and adjustment sets with is_d_separator, and simulate confounder and collider bias.

Source: https://www.pythoncharts.com/causal-inference/causal-dag-python/ | Published: 2026-11-27 | Author: Alex Scott | Category: Causal Inference | Tags: causal inference, causal dag, directed acyclic graph, confounding, collider, networkx, matplotlib

To draw a causal DAG (directed acyclic graph) in Python, add each cause-and-effect
arrow to a `networkx.DiGraph`, give every node an `(x, y)` position, and call
`nx.draw_networkx()`. NetworkX can also check which variables you need to
control for with `nx.is_d_separator()`. This post uses NetworkX 3.7 and
Matplotlib 3.11.

## Quick Example

Does a loyalty program raise spending? Income affects who joins and how much
they spend, visits are one route by which the program works, and complaints
come after both the program and spending.

```python
import matplotlib.pyplot as plt
import networkx as nx

G = nx.DiGraph([
    ("Income", "Program"), ("Income", "Spend"),
    ("City", "Income"), ("City", "Program"),
    ("Program", "Visits"), ("Visits", "Spend"),
    ("Program", "Spend"),
    ("Program", "Reviews"), ("Spend", "Reviews"),
])
pos = {"City": (0, 2), "Income": (1.6, 2), "Program": (0, 1),
       "Visits": (0.8, 0.35), "Spend": (1.6, 1), "Reviews": (0.8, -0.45)}

colors = {"Program": "#f2a65a", "Spend": "#6ab187"}

fig, ax = plt.subplots(figsize=(7.5, 5))
nx.draw_networkx(
    G, pos, ax=ax,
    node_size=3600, node_color=[colors.get(n, "#dce3ea") for n in G],
    edgecolors="#33414e", font_size=10,
    arrowsize=18, width=1.4, edge_color="#33414e",
)
ax.margins(0.12)
ax.axis("off")
plt.show()
```

![Causal diagram with arrows from city and income into program membership and spend, a path from program through visits to spend, and arrows from program and spend into reviews](https://www.pythoncharts.com/causal-inference/causal-dag-python/images/causal-dag-quick-example.png)

Pass the same `node_size` to every drawing call. NetworkX uses it to stop arrows
at the edge of a node, so a mismatch hides the arrowheads.

## Draw boxes with labels that fit

Long names don't fit in circles. Draw each label as a text box and each arrow
with `ax.annotate()`, which gives you full control:

```python
def draw_dag(G, pos, ax, highlight=(), colors=None):
    colors = colors or {}
    boxes = {}
    for node, (x, y) in pos.items():
        boxes[node] = ax.text(
            x, y, node, ha="center", va="center", fontsize=11, zorder=3,
            bbox=dict(boxstyle="round,pad=0.6", ec="#33414e",
                      fc=colors.get(node, "white")))
    for a, b in G.edges:
        red = (a, b) in highlight
        ax.annotate(
            "", xy=pos[b], xytext=pos[a],
            arrowprops=dict(
                arrowstyle="-|>", mutation_scale=18,
                color="#c0392b" if red else "#33414e", lw=2.4 if red else 1.2,
                patchA=boxes[a].get_bbox_patch(),
                patchB=boxes[b].get_bbox_patch(), shrinkA=2, shrinkB=2))
    xs, ys = zip(*pos.values())
    ax.set_xlim(min(xs) - 0.4, max(xs) + 0.4)
    ax.set_ylim(min(ys) - 0.3, max(ys) + 0.3)
    ax.axis("off")

names = {"City": "City size", "Income": "Household\nincome",
         "Program": "Loyalty\nprogram", "Visits": "Store visits",
         "Spend": "Monthly\nspend", "Reviews": "Leaves a\nreview"}
H = nx.relabel_nodes(G, names)
H_pos = {names[n]: xy for n, xy in pos.items()}

fig, ax = plt.subplots(figsize=(7.5, 5))
draw_dag(H, H_pos, ax, colors={names[n]: c for n, c in colors.items()})
plt.show()
```

![The same causal diagram drawn with rounded boxes holding two-line labels and arrows that stop at the box edges](https://www.pythoncharts.com/causal-inference/causal-dag-python/images/causal-dag-boxes.png)

`patchA` and `patchB` tell Matplotlib to clip each arrow at the two boxes.

## Lay out a DAG automatically

With many nodes, place them in layers: causes on the left, effects to the right.
`nx.topological_generations()` returns those layers, and sorting each one keeps
the vertical order the same on every run. Here is a larger graph of
what drives sales:

```python
M = nx.DiGraph([
    ("Season", "Ads"), ("Season", "Price"), ("Budget", "Ads"),
    ("Rivals", "Price"), ("Rivals", "Sales"),
    ("Ads", "Searches"), ("Ads", "Sales"), ("Searches", "Sales"),
    ("Price", "Sales"),
])
layers = {i: sorted(nodes)
          for i, nodes in enumerate(nx.topological_generations(M))}
for i, nodes in layers.items():
    print(i, nodes)

auto_pos = nx.multipartite_layout(M, subset_key=layers)
# Nudge one node so no arrow runs behind another
x, y = auto_pos["Searches"]
auto_pos["Searches"] = (x, y + 0.35)

fig, ax = plt.subplots(figsize=(8, 4.8))
nx.draw_networkx(M, auto_pos, ax=ax, node_size=2800, node_color="#cfe3f4",
                 font_size=10, arrowsize=16)
ax.margins(0.12)
ax.axis("off")
plt.show()
```

```text
0 ['Budget', 'Rivals', 'Season']
1 ['Ads', 'Price']
2 ['Searches']
3 ['Sales']
```

![Automatically layered causal diagram of marketing variables running left to right, from season, budget and rivals to sales](https://www.pythoncharts.com/causal-inference/causal-dag-python/images/causal-dag-layered.png)

An automatic layout can run an arrow behind a node. The positions are a plain
dictionary, so you can move any node by editing its entry in `auto_pos`.

`nx.is_directed_acyclic_graph(M)` confirms there are no loops, which a DAG
requires; the layout function raises an error if there is one.

## Find the backdoor paths

A backdoor path connects the treatment and outcome and starts with an arrow
*into* the treatment. These paths can create an association that isn't caused by
the treatment.

```python
paths = nx.all_simple_paths(G.to_undirected(), "Program", "Spend")
backdoor = [p for p in paths if G.has_edge(p[1], p[0])]

for path in backdoor:
    steps = path[0]
    for a, b in zip(path, path[1:]):
        steps += f" -> {b}" if G.has_edge(a, b) else f" <- {b}"
    print(steps)
```

```text
Program <- Income -> Spend
Program <- City -> Income -> Spend
```

## Which variables should I control for?

Delete the arrows leaving the treatment, then ask whether a set of variables
separates treatment from outcome in what's left. This is the backdoor
criterion. The set also must not contain anything caused by the treatment.

```python
from itertools import combinations

no_effects = G.copy()
no_effects.remove_edges_from(list(G.out_edges("Program")))
after_treatment = nx.descendants(G, "Program")

for k in range(3):
    for z in combinations(["City", "Income", "Visits", "Reviews"], k):
        blocks = nx.is_d_separator(no_effects, {"Program"}, {"Spend"}, set(z))
        valid = blocks and not (set(z) & after_treatment)
        if valid:
            print("Valid adjustment set:", set(z) or "{}")
```

```text
Valid adjustment set: {'Income'}
Valid adjustment set: {'Income', 'City'}
```

`Income` alone is enough: it sits on both backdoor paths. `City` alone leaves the
path through `Income` open. To highlight the backdoor arrows on the chart, pass
them to `draw_dag()`:

```python
red = {(names[a], names[b]) if G.has_edge(a, b) else (names[b], names[a])
       for path in backdoor for a, b in zip(path, path[1:])}

fig, ax = plt.subplots(figsize=(7.5, 5))
draw_dag(H, H_pos, ax, highlight=red,
         colors={names["Program"]: "#f2a65a", names["Spend"]: "#6ab187",
                 names["Income"]: "#f4d35e"})
plt.show()
```

![Causal diagram with the backdoor arrows between city, income, program and spend in red and household income highlighted as the adjustment variable](https://www.pythoncharts.com/causal-inference/causal-dag-python/images/causal-dag-backdoor.png)

## What happens if I control for the wrong variable?

Simulating data from the graph shows the effect of each choice. Here the program
adds $8 directly and $4 through extra visits, so its total effect is $12.

```python
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

rng = np.random.default_rng(173)
n = 100_000
city = rng.normal(size=n)
income = 0.6 * city + rng.normal(size=n)
program = rng.binomial(1, 1 / (1 + np.exp(-(0.9 * income + 0.5 * city))))
visits = 3 + 1.0 * program + rng.normal(size=n)
spend = 40 + 8 * program + 4 * visits + 10 * income + rng.normal(0, 8, n)
reviews = 0.15 * spend + 2 * program + rng.normal(0, 3, n)
data = pd.DataFrame(dict(City=city, Income=income, Program=program,
                         Visits=visits, Spend=spend, Reviews=reviews))

models = {
    "Nothing": "Spend ~ Program",
    "City": "Spend ~ Program + City",
    "Income": "Spend ~ Program + Income",
    "Income + Visits\n(mediator)": "Spend ~ Program + Income + Visits",
    "Income + Reviews\n(collider)": "Spend ~ Program + Income + Reviews",
}
estimates = pd.Series({name: smf.ols(f, data).fit().params["Program"]
                       for name, f in models.items()})
print(estimates.rename(lambda s: s.replace("\n", " ")).round(1))

fig, ax = plt.subplots(figsize=(8, 4.2))
good = np.isclose(estimates, 12, atol=0.5)
bars = ax.barh(estimates.index, estimates,
               color=np.where(good, "#6ab187", "#b8bec6"))
ax.bar_label(bars, fmt="{:.1f}", padding=4)
ax.axvline(12, color="#c0392b", ls="--", label="True total effect (12)")
ax.invert_yaxis()
ax.set_xlim(0, 28)
ax.set_xlabel("Estimated effect of the program on spend ($)")
ax.set_ylabel("Controlled for")
ax.legend(loc="lower right")
plt.show()
```

```text
Nothing                         23.2
City                            19.7
Income                          11.9
Income + Visits (mediator)       7.9
Income + Reviews (collider)      7.7
dtype: float64
```

![Bar chart of estimated program effect under five control sets, where only controlling for income matches the true value of 12](https://www.pythoncharts.com/causal-inference/causal-dag-python/images/causal-dag-bias.png)

Without controls the estimate is 23.2, nearly double the truth, and `City`
only removes part of that. Adding `Visits` holds fixed one of the ways the
program works, leaving about the $8 direct effect. Adding `Reviews` is also
wrong: it is a result of both the program and spending, so comparing customers
with the same review behavior distorts the relationship between them. More
controls aren't automatically better.

## Confounder, mediator or collider?

| Role | Shape | Control for it? |
|---|---|---|
| Confounder | Treatment ← Z → Outcome | Yes, or another variable that blocks the same path |
| Mediator | Treatment → Z → Outcome | No, if you want the total effect |
| Collider | Treatment → Z ← Outcome | No, it opens a false association |

```python
shapes = {"Confounder": [("Z", "T"), ("Z", "Y"), ("T", "Y")],
          "Mediator": [("T", "Z"), ("Z", "Y")],
          "Collider": [("T", "Z"), ("Y", "Z"), ("T", "Y")]}
small_pos = {"T": (0, 0), "Y": (2, 0), "Z": (1, 0.8)}

fig, axes = plt.subplots(1, 3, figsize=(9, 2.6))
for ax, (title, edges) in zip(axes, shapes.items()):
    draw_dag(nx.DiGraph(edges), small_pos, ax,
             colors={"T": "#f2a65a", "Y": "#6ab187"})
    ax.set_title(title)
plt.show()
```

![Three small causal diagrams showing a confounder pointing into treatment and outcome, a mediator between them, and a collider receiving arrows from both](https://www.pythoncharts.com/causal-inference/causal-dag-python/images/causal-dag-roles.png)

## Practical tips

- The graph encodes your assumptions. Code can tell you what follows from it, not whether it is right.
- A missing arrow is a strong claim that one variable doesn't affect another.
- Include unmeasured causes as nodes (a gray box works) so it's clear when no valid adjustment set exists among your columns.
- To go from the graph to an estimate with built-in checks, see [DoWhy](https://www.pythoncharts.com/causal-inference/dowhy-python/).
- For large graphs, Graphviz produces better layouts than the tools here, but it needs a separate system install.

## Similar Topics

- [How to Draw a Network Graph in Python](https://www.pythoncharts.com/python/network-graph-python/)
- [Propensity Score Matching in Python](https://www.pythoncharts.com/causal-inference/propensity-score-matching-python/)
- [Causal Inference in Python: How to Choose a Method](https://www.pythoncharts.com/causal-inference/causal-inference-python-guide/)
