Printing xgb's 'plot_importance' via st.pyplot

Summary

Hi, currently I am trying to plot a feature importance plot from the xgb library and display it in my Streamlit app via st.pyplot.

However, when trying to launch the app, it raises an attribute error:

AttributeError: ‘AxesSubplot’ object has no attribute ‘savefig’

I also already experimented with adding an ax argument as has been done here, but it doesn’t quite solve the case for me.

Thank you in advance!

Steps to reproduce

Code snippet:

# Import packages
import numpy as np 
import pandas as pd
import streamlit as st
from xgboost import XGBClassifier, plot_importance
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

...

# Plot the most important features
    fig = plot_importance(model)
    st.pyplot(fig)

Expected behavior:

I expect the plot to be displayed within the app page.

Actual behavior:

An attribute error is raised:

AttributeError: ‘AxesSubplot’ object has no attribute ‘savefig’

Debug info

  • Streamlit version: 1.14.0
  • Python version: 3.9.10

Edit: i also tried solving the problem via the following code.

# Plot the most important features
    plot_importance(model)
    fig = pyplot.show()
    st.pyplot(fig)

In that case, the plot is generally displayed but I receive the usual PyplotGlobalUseWarning:

PyplotGlobalUseWarning: You are calling st.pyplot() without any arguments. After December 1st, 2020, we will remove the ability to do this as it requires the use of Matplotlib’s global figure object, which is not thread-safe.

To future-proof this code, you should pass in a figure as shown below …

Hi @kevin-kohler,

Good question and welcome to the Streamlit community! :wave: :partying_face:

I’ve encountered this issue numerous times in the past when another package uses Matplotlib under the hood.

The AxesSubplot object contains a .figure attribute. You need to pass that underlying figure object to st.pyplot() like so:

Code

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier, plot_importance
import streamlit as st

@st.experimental_memo
def return_model():
    data = load_iris()
    X_train, X_test, y_train, y_test = train_test_split(
        data["data"], data["target"], test_size=0.2
    )
    # create model instance
    bst = XGBClassifier(
        n_estimators=2, max_depth=2, learning_rate=1, objective="binary:logistic"
    )
    # fit model
    bst.fit(X_train, y_train)
    # make predictions
    preds = bst.predict(X_test)
    return bst

model = return_model()
# plot feature importance
st.pyplot(plot_importance(model).figure) # Pass the underlying figure

Output:

Happy Streamlit-ing! :balloon:
Snehan

1 Like

Thank you a thousand times Snehan, this is the solution! Afrer adding the .figure attribute, the app displays the plot without any warning or error. Thank you! :star_struck:

1 Like