5

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?

wisamb
  • 470
  • 3
  • 11
  • 1
    can this help? https://stackoverflow.com/questions/3428448/reducing-the-size-as-in-area-of-the-graph-generated-by-graphviz – Joe Oct 10 '18 at 06:40
  • Can you set rankdir to LR - see if the graph gets generated from left to right instead of top to bottom. I know how to do this directly but not from python. – cup Oct 10 '18 at 06:48

1 Answers1

2

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?

kirogasa
  • 627
  • 5
  • 19