How to Plot a Decision Tree in Python with scikit-learn

Plot a decision tree with scikit-learn's plot_tree, print its rules with export_text, and prune an overgrown tree with ccp_alpha so it stays readable and generalizes.

To plot a decision tree in scikit-learn, fit a DecisionTreeClassifier and pass it to sklearn.tree.plot_tree(tree, feature_names=..., class_names=..., filled=True), drawing into a Matplotlib axis. For a plain-text version of the same rules, use sklearn.tree.export_text. A tree is only readable when it is small, so the practical skill is keeping it small with max_depth, min_samples_leaf or pruning. The code targets scikit-learn 1.9.

Quick Example

This fits a depth-3 tree on simulated customer-churn data and plots it. Each box shows the split rule, the share of training samples, the class mix (value) and the majority class.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text, plot_tree

# Sample data: customer churn
rng = np.random.default_rng(31)
n = 1500
tenure = rng.integers(1, 61, n)
monthly = rng.normal(70, 25, n).clip(20, 150)
tickets = rng.poisson(1.5, n)
contract = rng.choice(["month-to-month", "annual"], n, p=[0.6, 0.4])
logit = (-0.3 + 2.4 * (contract == "month-to-month") - 0.10 * tenure + 0.02 * (monthly - 70) + 0.6 * tickets - 1.5)
churn = rng.random(n) < 1 / (1 + np.exp(-logit))
X = pd.DataFrame({"tenure_months": tenure, "monthly_charge": monthly.round(1), "support_tickets": tickets,
                  "month_to_month": (contract == "month-to-month").astype(int)})
X_train, X_test, y_train, y_test = train_test_split(X, churn, test_size=0.3, random_state=0)
print("majority-class test accuracy:", round(1 - float(y_test.mean()), 3))

tree = DecisionTreeClassifier(max_depth=3, min_samples_leaf=30, random_state=0).fit(X_train, y_train)
print("depth-3 test accuracy:", round(tree.score(X_test, y_test), 3))

fig, ax = plt.subplots(figsize=(13, 6.5))
plot_tree(tree, feature_names=X.columns, class_names=["stays", "churns"], filled=True, rounded=True,
          impurity=False, proportion=True, precision=2, fontsize=10, ax=ax)
fig.tight_layout()

A depth-3 decision tree for customer churn. The root splits on tenure at 23.5 months. Most boxes are orange (predict stays); one leaf, month-to-month customers with short tenure, is blue and predicts churn with a 72 percent churn share

Predicting "stays" for everyone would be right 82.4% of the time on the test set, since only about 18% of customers churn. The depth-3 tree gets 86.0%. Only one leaf predicts churn: short-tenure, month-to-month customers (about 11% of the data, 72% of whom churned). Blue boxes are leaning toward the second class and orange toward the first, and a darker color means a purer node.

How Do I Read a Scikit-learn Decision Tree Plot?

Starting at the root, follow the True branch (left) when the condition in the box holds, and the False branch (right) otherwise. Each box shows:

Line Meaning
tenure_months <= 23.5 The split rule. Absent in leaf boxes
samples = 36.1% Share of training rows reaching this node (with proportion=True; otherwise a count)
value = [0.6, 0.4] Class mix at this node, in the order of tree.classes_
class = stays The majority class, which is the prediction if this were a leaf

Useful plot_tree arguments:

Argument Use
feature_names, class_names Readable labels instead of x[0] and class = 0. Class names go in the order of tree.classes_
filled=True Colors nodes by majority class and purity
max_depth=2 Draws only the top levels of a large tree
proportion=True Shows percentages instead of sample counts
impurity=False Hides the Gini value, which usually clutters the plot
fontsize, ax Must be an integer font size, and an axis to draw on. Set a large figsize, since the default is cramped

How Do I Print a Decision Tree as Text Rules?

export_text gives the same tree as indented rules, which pastes well into code reviews and documents and stays readable for deeper trees:

print(export_text(tree, feature_names=list(X.columns)))
|--- tenure_months <= 23.50
|   |--- month_to_month <= 0.50
|   |   |--- support_tickets <= 1.50
|   |   |   |--- class: False
|   |   |--- support_tickets >  1.50
|   |   |   |--- class: False
|   |--- month_to_month >  0.50
|   |   |--- tenure_months <= 13.50
|   |   |   |--- class: True
|   |   |--- tenure_months >  13.50
|   |   |   |--- class: False
|--- tenure_months >  23.50
|   |--- tenure_months <= 34.50
|   |   |--- monthly_charge <= 56.10
|   |   |   |--- class: False
|   |   |--- monthly_charge >  56.10
|   |   |   |--- class: False
|   |--- tenure_months >  34.50
|   |   |--- support_tickets <= 1.50
|   |   |   |--- class: False
|   |   |--- support_tickets >  1.50
|   |   |   |--- class: False

Here class: True means "churns", since the target is a boolean. Pass class_names=["stays", "churns"] to print readable labels. export_text stops at max_depth=10 by default.

What Does an Unpruned Tree Look Like?

With no limits, a tree keeps splitting until every training row is classified. That gives a depth of 17 and 180 leaves on this data, with 100% training accuracy but 84.4% test accuracy, which is worse than the depth-3 tree. It is also unreadable. plot_tree(..., max_depth=2) shows only the top of it:

deep = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print("depth:", deep.get_depth(), "leaves:", deep.get_n_leaves())
print("train:", round(deep.score(X_train, y_train), 3), "test:", round(deep.score(X_test, y_test), 3))

fig, ax = plt.subplots(figsize=(13, 6))
plot_tree(deep, max_depth=2, feature_names=X.columns, class_names=["stays", "churns"], filled=True,
          impurity=False, proportion=True, fontsize=9, ax=ax)
ax.set_title(f"Unpruned tree: depth {deep.get_depth()}, {deep.get_n_leaves()} leaves (only the top 2 levels shown)")
fig.tight_layout()

The top three levels of an unpruned decision tree with grey collapsed nodes at the bottom, titled depth 17 with 180 leaves

The top of the tree matches the small one. Everything below is the tree fitting noise, which is why constraining it works.

How Do I Prune a Decision Tree?

Three ways to keep a tree small, from simplest to most flexible:

Parameter Effect
max_depth Hard limit on levels
min_samples_leaf Each leaf must hold at least this many rows (an integer, or a fraction if a float)
ccp_alpha Cost-complexity pruning: grow a full tree, then remove the branches that add the least accuracy per leaf. Larger values prune more

cost_complexity_pruning_path lists the candidate alpha values. Choose by cross-validation on the training set, not by looking at the test set:

from sklearn.model_selection import cross_val_score

path = DecisionTreeClassifier(random_state=0).cost_complexity_pruning_path(X_train, y_train)
candidates = path.ccp_alphas[:-1]    # the last alpha prunes everything down to the root
alphas = candidates[np.unique(np.linspace(0, len(candidates) - 1, 40).astype(int))]

rows = []
for a in alphas:
    t = DecisionTreeClassifier(random_state=0, ccp_alpha=a)
    cv = cross_val_score(t, X_train, y_train, cv=5).mean()
    t.fit(X_train, y_train)
    rows.append((a, t.get_n_leaves(), t.score(X_train, y_train), cv))
r = pd.DataFrame(rows, columns=["alpha", "leaves", "train", "cv"])
best = r.loc[r.cv.idxmax()]
pruned = DecisionTreeClassifier(random_state=0, ccp_alpha=best.alpha).fit(X_train, y_train)
print("best alpha", round(best.alpha, 5), "leaves", int(best.leaves), "cv", round(best.cv, 3),
      "test", round(pruned.score(X_test, y_test), 3))

fig, ax = plt.subplots(figsize=(8, 4.4))
ax.plot(r.alpha, r.train, color="#e76f51", lw=2, label="Train accuracy")
ax.plot(r.alpha, r.cv, color="#1b6ca8", lw=2, label="Cross-validated accuracy")
ax.axvline(best.alpha, color="gray", ls=":", label=f"Best CV accuracy: {int(best.leaves)} leaves")
ax.set_xscale("log")
ax.set_xlabel("ccp_alpha (higher means more pruning)")
ax.set_ylabel("Accuracy")
ax.legend()
fig.tight_layout()

Train accuracy falling from 1.0 to about 0.81 and cross-validated accuracy rising from about 0.81 to a peak near 0.856, as the pruning strength ccp_alpha increases, with a dotted line at the best value of 6 leaves

Training accuracy falls steadily as pruning increases, while cross-validated accuracy rises until about 6 leaves (0.856) and then declines. The pruned tree scores 87.3% on the test set, against 84.4% for the unpruned one. Pass ccp_alpha=best.alpha to the final model, and plot it with plot_tree to get a readable result.

Are There Alternatives to plot_tree for Large Trees?

Two options, both of which render with Graphviz rather than Matplotlib. sklearn.tree.export_graphviz ships with scikit-learn and writes the tree as DOT text, which you can paste into any Graphviz viewer or render with the graphviz package:

from sklearn.tree import export_graphviz

dot = export_graphviz(tree, feature_names=list(X.columns), class_names=["stays", "churns"],
                      filled=True, rounded=True)
print(dot.splitlines()[0], "...", len(dot.splitlines()), "lines")

Turning that text into an image needs the Graphviz program itself (the dot executable) plus pip install graphviz, which is a system install, not a Python one.

The dtreeviz package draws richer trees, with a histogram of each feature at every split and the class mix in each leaf. It also needs the Graphviz executable. dtreeviz.model(tree, X_train, y_train, feature_names=list(X.columns), target_name="churn", class_names=["stays", "churns"]).view() builds the figure (the API above is from dtreeviz 2.x). Reach for it when you need to present a tree to people, and stay with plot_tree and export_text for quick inspection.

Can I Trust a Single Decision Tree?

A single tree is easy to explain, but unstable: a small change in the training data can move the root split. If the tree is for explanation, check that its top splits persist across bootstrap samples or cross-validation folds. If you only need accuracy, a random forest or gradient boosting usually beats one tree, at the cost of the single readable diagram. Feature importance and SHAP plots recover some of that explanation for ensembles.

Practical Tips

  • Always compare with the majority-class baseline. On imbalanced data a tree can look accurate while predicting the majority class almost everywhere.
  • For a figure that fits a page, use max_depth=3 or 4 and fontsize 10 or more, and set figsize to something wide such as (13, 6.5).
  • Scaling is not needed for trees, and numeric thresholds like 23.5 are in the original units.
  • Use class_weight="balanced" if you want the tree to find the minority class more often, and expect more splits that predict it.
  • The numbers here come from one seeded simulation. The splits on a real dataset will be less clean.

Similar Topics