Using supertree (decision tree visualization library) inside Streamlit app?

Hello,

I am trying to embed the visualization produced by the supertree library (GitHub - mljar/supertree: Visualize decision trees in Python) in a Streamlit app.

Supertree produces visualization of decision trees inside Jupyter Notebooks, so that in principle it might be embeddable in Streamlit.

The minimal Streamlit app could be something like this:

import streamlit as st
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
from supertree import SuperTree

iris = load_iris()
X, y = iris.data, iris.target
model = DecisionTreeClassifier()
model.fit(X, y)
super_tree = SuperTree(model, X, y, iris.feature_names, iris.target_names)
super_tree.show_tree()

The app runs correctly and the last sentence shows in console the type of the object that is generated inside Supertree:

<IPython.core.display.HTML object>

But the app is blank. I have tried to use st.html() with no success, or trying to get that HTML object to be passed to Streamlit somehow, but found no way. Any help is highly appreciated!

I am using streamlit 1.41.1.
Many thanks in advance,
Miguel-Angel

st.html removes all JS scripts before rendering, so in this case use st.components.v1.html.

Also, exporting to html in supertree seems to only write directly to a file, so I used a NamedTemporaryFile:

from tempfile import NamedTemporaryFile

import streamlit as st
from streamlit.components.v1 import html
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
from supertree import SuperTree

iris = load_iris()
X, y = iris.data, iris.target
model = DecisionTreeClassifier()
model.fit(X, y)
super_tree = SuperTree(model, X, y, iris.feature_names, iris.target_names)

st.title("Supertree")
with NamedTemporaryFile(suffix=".html") as f:
    super_tree.save_html(f.name)
    html(f.read(), height=400)
3 Likes

Many thanks, that works perfectly!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.