wisamb
wisamb

Reputation: 502

graphviz plot too wide

I'm doing a practice exercise of creating a decision tree using graphviz in jupyter notebook. however, the decision tree is coming too wide. here is the code:

from sklearn.tree import export_graphviz
export_graphviz(tree, out_file="tree.dot", class_names=["malignant", "benign"], 
                feature_names=cancer.feature_names, impurity=False, filled=True)
with open("tree.dot") as f:
    dot_graph = f.read()
display(graphviz.Source(dot_graph))

and I get this: enter image description here

I have to scroll to see the left side of the decision tree. can I make the width smaller? how?

Upvotes: 5

Views: 4003

Answers (1)

kirogasa
kirogasa

Reputation: 949

If the node tree is spreading widely, you can try

  • add line breaks for long labels (node1 [label="line\nbreak"])
  • reduce nodes width and margin globally (node [width=0.1 margin=0])
  • reduce distance between nodes in row for graph (graph [nodesep=0.1])
  • reduce graph size (graph [size="3,3"])

Or you can put all the nodes in a column with rankdir=LR; edge[constraint=false], as in example below.
Image:
node column made with graphviz dot
Script:

digraph {
    graph [rankdir=LR ranksep=1]
    
    node[shape=box width=3]
    edge[constraint=false]
    
    A -> {B C}
    B -> {D E}
    C -> F
    D -> {G H}
    E -> I
    F -> {J T}
    G -> {K L}
    H -> {M N}
    J -> {O P}
}

Related question: Is it possible to generate a small GraphViz chart?

Upvotes: 3

Related Questions