How to create decision tree in graphviz

What is decision tree

Decision tree is a flowchart-like structure that represents a set of decisions and their possible consequences.

It is commonly used in machine learning, data mining, and statistics to model and analyze complex decision-making processes.

See Wikipedia for more information.

What are some of the examples of Decision trees

  • Customer segmentation
  • Credit scoring
  • Fraud detection
  • Medical diagnosis
  • Risk assessment
  • Marketing campaign analysis

What is Graphviz

Graphviz is an open-source graph visualization software that provides a way to represent structural information as diagrams of abstract graphs and networks.

It is widely used for visualizing complex data structures, such as trees, graphs, and networks.

Creating decision tree in Graphviz

Example graphviz code for decision tree

digraph DecisionTree {
    rankdir=TB; // Top-to-bottom layout
    nodesep=0.5; // Horizontal spacing
    ranksep=1.0; // Vertical spacing

    // Node Styles
    node [shape=rect, style=filled];

    // Root Node
    is_raining [label="Is it raining?", color=lightblue];

    // Level 1
    has_umbrella [label="Do you have an umbrella?", color=lightyellow];

    // Leaf Nodes
    take_umbrella [label="Take umbrella", color=lightgreen]; // Good outcome
    dont_go [label="Don't go outside", color=tomato]; // Negative outcome
    enjoy_walk [label="Enjoy your walk", color=lightgreen]; // Good outcome

    // Edges
    is_raining -> has_umbrella [label="Yes"];
    is_raining -> enjoy_walk [label="No"];
    has_umbrella -> take_umbrella [label="Yes"];
    has_umbrella -> dont_go [label="No"];

    // Rank alignment
    { rank=same; take_umbrella; dont_go; }
}

What is important about that which makes it look like decision tree, and not just flowchart:

  1. we use nodesep and ranksep to set the horizontal and vertical spacing between nodes.
  2. we use { rank=same; take_umbrella; dont_go; } to align the leaf nodes at the same rank.

graphviz

See in a playground here