Search code examples
pythonscikit-learntreejupyter-notebookgraphviz

How to resize the image of the tree using sklearn tree and export_graph_viz within a Jupyter Notebook


I am using export_graph_viz to visualize a decision tree but the image spreads out of view in my Jupyter Notebook.

If this was a pyplot figure I would use the command plt.figure(figsize = (12,7)) to constrain the visualization. But in this case I do not know how to proceed.

Below is a snapshot of my Jupyter Notebook and what I see:

enter image description here


Solution

  • You can save the visualized tree to a file and then show it with pyplot.

    Example:

    import matplotlib.pyplot as plt
    import pydotplus
    import matplotlib.image as mpimg
    import io
    
    from sklearn.externals.six import StringIO
    from sklearn.tree import export_graphviz
    
    dot_data = io.StringIO()
    
    export_graphviz(clf, out_file=dot_data, rounded=True, filled=True)
    
    filename = "tree.png"
    pydotplus.graph_from_dot_data(dot_data.getvalue()).write_png(filename)
    
    plt.figure(figsize=(12,12))
    img = mpimg.imread(filename)
    imgplot = plt.imshow(img)
    
    plt.show()
    

    Result: enter image description here