Decision Tree Visualization with Probabilities in ggplot2 (R)

The same plot in 14 other libraries — Python: Altair, Bokeh, lets-plot, Matplotlib, Plotly, plotnine, Pygal, Seaborn; Julia: Makie.jl; JavaScript: Chart.js, D3.js, Apache ECharts, Highcharts, MUI X Charts. Compare all 15 side by side: Decision Tree Visualization with Probabilities in Python, R, Julia and JavaScript.

A tree-structured diagram for sequential decision analysis, displaying decision nodes (squares), chance nodes (circles), and terminal outcome nodes (triangles) connected by branching paths. Each chance branch is labeled with probabilities, terminal nodes show payoff values, and Expected Monetary Values (EMV) are calculated via rollback at each node. Rejected (pruned) branches are visually marked, making it easy to trace the optimal decision path through a multi-stage problem.

Decision Tree Visualization with Probabilities rendered with ggplot2

Renders

R source (ggplot2)

#' anyplot.ai
#' tree-decision: Decision Tree Visualization with Probabilities
#' Library: ggplot2 4.0.3 | R 4.6.1
#' Quality: 85/100 | Updated: 2026-12-04

library(ggplot2)
library(ragg)

set.seed(42)

# Theme tokens (Imprint palette)
THEME       <- Sys.getenv("ANYPLOT_THEME", "light")
PAGE_BG     <- if (THEME == "light") "#FAF8F1" else "#1A1A17"
ELEVATED_BG <- if (THEME == "light") "#FFFDF6" else "#242420"
INK         <- if (THEME == "light") "#1A1A17" else "#F0EFE8"
INK_SOFT    <- if (THEME == "light") "#4A4A44" else "#B8B7B0"
INK_MUTED   <- if (THEME == "light") "#6B6A63" else "#A8A79F"

# Imprint palette positions used
COL_DEC  <- "#009E73"  # position 1 — decision nodes (brand green)
COL_CHC  <- "#C475FD"  # position 2 — chance nodes (violet)
COL_TERM <- "#4467A3"  # position 3 — terminal nodes (blue)
CHC_INK  <- "#1A1A17"  # dark text on the light violet chance nodes, both themes

# Tech startup product launch decision tree
# Stage 1: Launch vs. Skip (Skip = license the idea out, partner interest uncertain)
# Stage 2 (if Launch): Market Strong (p=0.6) vs. Weak (p=0.4)
# Stage 3 (if Strong): Expand vs. Maintain (Maintain faces steady or slumping demand)
#
# EMV rollback (in $K):
#   EMV(C1) = 0.7 * 150 + 0.3 * 90  = 132
#   EMV(D1) = max(Expand 300, Maintain 132) = 300  -> Expand wins
#   EMV(C0) = 0.6 * 300 + 0.4 * 20  = 188
#   EMV(C2) = 0.5 * 60 + 0.5 * 0    = 30
#   EMV(D0) = max(Launch 188, Skip 30) = 188        -> Launch wins

nodes <- data.frame(
  id     = c("D0",  "C0",  "D1",  "C1",  "C2",  "T1",  "T2",  "T3",  "T4",  "T5",  "T6"),
  type   = c("dec", "chc", "dec", "chc", "chc", "term","term","term","term","term","term"),
  x      = c(1.0,   2.9,   4.8,   6.7,   2.9,   6.7,   8.6,   8.6,   4.8,   4.8,   4.8),
  y      = c(-0.1,  0.8,   1.5,   0.9,  -0.9,   2.2,   1.3,   0.5,   0.0,  -0.5,  -1.3),
  payoff = c(NA,    NA,    NA,    NA,    NA,    300,   150,   90,    20,    60,    0),
  pruned = c(FALSE, FALSE, FALSE, TRUE,  TRUE,  FALSE, TRUE,  TRUE,  FALSE, TRUE,  TRUE),
  stringsAsFactors = FALSE
)

edges <- data.frame(
  from   = c("D0",     "D0",   "C0",           "C0",          "D1",     "D1",
             "C1",             "C1",             "C2",             "C2"),
  to     = c("C0",     "C2",   "D1",           "T4",          "T1",     "C1",
             "T2",             "T3",             "T5",             "T6"),
  label  = c("Launch", "Skip", "p=0.6\nStrong", "p=0.4\nWeak", "Expand", "Maintain",
             "p=0.7\nSteady",   "p=0.3\nSlump",    "p=0.5\nPartner",  "p=0.5\nNone"),
  prob   = c(NA, NA, 0.6, 0.4, NA, NA, 0.7, 0.3, 0.5, 0.5),
  pruned = c(FALSE, TRUE,  FALSE,          FALSE,         FALSE,    TRUE,
             TRUE,             TRUE,             TRUE,             TRUE),
  mark   = c(FALSE, TRUE,  FALSE,          FALSE,         FALSE,    TRUE,
             FALSE,            FALSE,            FALSE,            FALSE),
  stringsAsFactors = FALSE
)

# EMV of each chance node from its branches, shown inside the node
# (decision nodes take the best child: D1 = max(T1, C1), D0 = max(C0, C2))
emv <- c(
  C1 = sum(c(150, 90) * c(0.7, 0.3)),
  C2 = sum(c(60, 0)   * c(0.5, 0.5))
)
emv["C0"] <- 0.6 * 300 + 0.4 * 20
emv["D1"] <- max(300, emv[["C1"]])
emv["D0"] <- max(emv[["C0"]], emv[["C2"]])
nodes$emv_lbl <- ifelse(nodes$id %in% names(emv), paste0("$", round(emv[nodes$id]), "K"), NA)

# Attach node coordinates to edges
fi       <- match(edges$from, nodes$id)
ti       <- match(edges$to,   nodes$id)
edges$x0 <- nodes$x[fi];  edges$y0 <- nodes$y[fi]
edges$x1 <- nodes$x[ti];  edges$y1 <- nodes$y[ti]

# Branch label at 38% from source; offset above/below the line depending on slope
edges$lx <- edges$x0 + 0.38 * (edges$x1 - edges$x0)
edges$ly <- edges$y0 + 0.38 * (edges$y1 - edges$y0)
edges$dy <- ifelse(edges$y1 >= edges$y0, 0.27, -0.27)

# Pruned-mark position at 70% from source
edges$px <- edges$x0 + 0.70 * (edges$x1 - edges$x0)
edges$py <- edges$y0 + 0.70 * (edges$y1 - edges$y0)

# Right-pointing triangle polygons for terminal nodes
hw <- 0.14
term_rows <- which(nodes$type == "term")
tri_frames <- lapply(seq_along(term_rows), function(i) {
  ni <- term_rows[i]
  data.frame(
    x      = c(nodes$x[ni] - hw, nodes$x[ni] - hw, nodes$x[ni] + hw),
    y      = c(nodes$y[ni] - hw * 0.85, nodes$y[ni] + hw * 0.85, nodes$y[ni]),
    pruned = nodes$pruned[ni],
    grp    = i
  )
})
tri_data <- do.call(rbind, tri_frames)

# Subsets for conditional styling
e_live  <- edges[!edges$pruned, ]
e_dead  <- edges[edges$pruned, ]
e_mark  <- edges[edges$mark, ]
t_live  <- tri_data[!tri_data$pruned, ]
t_dead  <- tri_data[tri_data$pruned, ]
n_dec   <- nodes[nodes$type == "dec", ]
n_chc   <- nodes[nodes$type == "chc" & !nodes$pruned, ]
n_chcd  <- nodes[nodes$type == "chc" &  nodes$pruned, ]
n_emv   <- nodes[!is.na(nodes$emv_lbl) & nodes$type == "dec", ]
n_emvc  <- nodes[!is.na(nodes$emv_lbl) & nodes$type == "chc" & !nodes$pruned, ]
n_emvcd <- nodes[!is.na(nodes$emv_lbl) & nodes$type == "chc" &  nodes$pruned, ]
n_paylv <- nodes[nodes$type == "term" & !nodes$pruned, ]
n_paydt <- nodes[nodes$type == "term" &  nodes$pruned, ]

KEY_Y <- -1.85

# Faded fills for pruned nodes: opaque blends toward the page so edges never show through
fade <- function(col, amount) {
  rgb(t(col2rgb(col) * (1 - amount) + col2rgb(PAGE_BG) * amount), maxColorValue = 255)
}
FADE_CHC  <- fade(COL_CHC, 0.65)
FADE_TERM <- fade(COL_TERM, 0.70)

p <- ggplot() +
  # Edges: active
  geom_segment(
    data = e_live,
    aes(x = x0, y = y0, xend = x1, yend = y1),
    color = INK_SOFT, linewidth = 1.0
  ) +
  # Edges: pruned (dashed, muted)
  geom_segment(
    data = e_dead,
    aes(x = x0, y = y0, xend = x1, yend = y1),
    color = INK_MUTED, linewidth = 0.5, linetype = "dashed", alpha = 0.55
  ) +
  # Terminal triangles: active
  geom_polygon(
    data = t_live,
    aes(x = x, y = y, group = grp),
    fill = COL_TERM, color = INK_SOFT
  ) +
  # Terminal triangles: pruned (faded)
  geom_polygon(
    data = t_dead,
    aes(x = x, y = y, group = grp),
    fill = FADE_TERM, color = INK_MUTED
  ) +
  # Chance nodes (circles): active and pruned
  geom_point(
    data = n_chc,
    aes(x = x, y = y),
    shape = 21, size = 14.5, fill = COL_CHC, color = INK_SOFT, stroke = 0.5
  ) +
  geom_point(
    data = n_chcd,
    aes(x = x, y = y),
    shape = 21, size = 14.5, fill = FADE_CHC, color = INK_MUTED, stroke = 0.5
  ) +
  # Decision nodes (squares)
  geom_point(
    data = n_dec,
    aes(x = x, y = y),
    shape = 22, size = 14.5, fill = COL_DEC, color = INK_SOFT, stroke = 0.5
  ) +
  # EMV values inside decision/chance nodes
  geom_text(
    data = n_emv,
    aes(x = x, y = y, label = emv_lbl),
    color = "white", size = 2.7, fontface = "bold"
  ) +
  geom_text(
    data = n_emvc,
    aes(x = x, y = y, label = emv_lbl),
    color = CHC_INK, size = 2.7, fontface = "bold"
  ) +
  geom_text(
    data = n_emvcd,
    aes(x = x, y = y, label = emv_lbl),
    color = INK_SOFT, size = 2.7, fontface = "bold"
  ) +
  # Branch labels: active
  geom_label(
    data = e_live,
    aes(x = lx, y = ly + dy, label = label),
    color = INK_SOFT, fill = ELEVATED_BG, size = 2.9, lineheight = 0.85,
    label.padding = unit(0.13, "lines"), linewidth = 0
  ) +
  # Branch labels: pruned
  geom_label(
    data = e_dead,
    aes(x = lx, y = ly + dy, label = label),
    color = INK_MUTED, fill = ELEVATED_BG, size = 2.9, lineheight = 0.85,
    label.padding = unit(0.13, "lines"), linewidth = 0
  ) +
  # Double-strike pruned mark on the rejected options
  geom_text(
    data = e_mark,
    aes(x = px, y = py),
    label = "//", color = INK_MUTED, size = 3.8
  ) +
  # Payoff labels: active terminals (right of triangle)
  geom_text(
    data = n_paylv,
    aes(x = x + hw + 0.09, y = y, label = paste0("$", payoff, "K")),
    color = INK, size = 3.4, fontface = "bold", hjust = 0
  ) +
  # Payoff labels: pruned terminals
  geom_text(
    data = n_paydt,
    aes(x = x + hw + 0.09, y = y, label = paste0("$", payoff, "K")),
    color = INK_MUTED, size = 3.2, hjust = 0, alpha = 0.6
  ) +
  # Key: Decision node
  annotate("point", x = 1.0, y = KEY_Y, shape = 22, size = 5,
           fill = COL_DEC, color = INK_SOFT) +
  annotate("text", x = 1.18, y = KEY_Y, label = "Decision",
           hjust = 0, size = 3.0, color = INK_SOFT) +
  # Key: Chance node
  annotate("point", x = 2.75, y = KEY_Y, shape = 21, size = 5,
           fill = COL_CHC, color = INK_SOFT) +
  annotate("text", x = 2.93, y = KEY_Y, label = "Chance",
           hjust = 0, size = 3.0, color = INK_SOFT) +
  # Key: Terminal node (small right-pointing triangle)
  annotate("polygon",
           x = c(4.35 - 0.07, 4.35 - 0.07, 4.35 + 0.07),
           y = c(KEY_Y - 0.06, KEY_Y + 0.06, KEY_Y),
           fill = COL_TERM, color = INK_SOFT) +
  annotate("text", x = 4.50, y = KEY_Y, label = "Terminal",
           hjust = 0, size = 3.0, color = INK_SOFT) +
  # Key: pruned (rejected) branch, dashed with the double strike
  annotate("segment", x = 5.95, xend = 6.55, y = KEY_Y, yend = KEY_Y,
           color = INK_MUTED, linewidth = 0.5, linetype = "dashed", alpha = 0.7) +
  annotate("text", x = 6.25, y = KEY_Y, label = "//", color = INK_MUTED, size = 3.8) +
  annotate("text", x = 6.70, y = KEY_Y, label = "Pruned (rejected)",
           hjust = 0, size = 3.0, color = INK_SOFT) +
  coord_cartesian(xlim = c(0.35, 9.9), ylim = c(-2.15, 2.65), expand = FALSE) +
  labs(title = "tree-decision · r · ggplot2 · anyplot.ai") +
  theme_void() +
  theme(
    plot.background  = element_rect(fill = PAGE_BG, color = PAGE_BG),
    panel.background = element_rect(fill = PAGE_BG, color = NA),
    plot.title       = element_text(
      color = INK, size = 12, hjust = 0.5,
      margin = margin(t = 14, b = 8)
    ),
    plot.margin = margin(t = 5, r = 40, b = 20, l = 10)
  )

ggsave(
  filename = sprintf("plot-%s.png", THEME),
  plot     = p,
  device   = ragg::agg_png,
  width    = 8,
  height   = 4.5,
  units    = "in",
  dpi      = 400
)

Retrieve this implementation

Runnable source as JSON, for any HTTP client: https://api.anyplot.ai/specs/tree-decision/ggplot2/code. Any spec id and library id listed in llms-full.txt fit the same URL shape; every URL below is complete and callable.

{
  "spec_id": "tree-decision",
  "language": "r",
  "library": "ggplot2",
  "page": "https://anyplot.ai/tree-decision/r/ggplot2",
  "hub": "https://anyplot.ai/tree-decision",
  "code_json": "https://api.anyplot.ai/specs/tree-decision/ggplot2/code",
  "spec_json": "https://api.anyplot.ai/specs/tree-decision",
  "render_light_png": "https://storage.googleapis.com/anyplot-images/plots/tree-decision/r/ggplot2/plot-light.png",
  "render_dark_png": "https://storage.googleapis.com/anyplot-images/plots/tree-decision/r/ggplot2/plot-dark.png",
  "quality_score": 85.0,
  "license": "MIT",
  "guide": "https://anyplot.ai/llms.txt"
}

Part of Decision Tree Visualization with Probabilities on anyplot.ai.

Other implementations