Cache matplotlib figure


Streamlit hangs (no output, can only be killed) when I apply @st.cache decorator to function that returns matplotlib figure.


Caching works for matplotlib figures.

Steps to reproduce

This snippet demonstrates the issue here:

import streamlit as st
import numpy as np
import matplotlib.pyplot as plt

def plot():
    arr = np.random.normal(1, 1, size=100)
    fig, ax = plt.subplots()
    ax.hist(arr, bins=20)
    return fig


Hello @StefanBrand, welcome to the community!

Regarding caching Matplotlib figures, I think I saw something similar here: st.cache doesn't work with matplotlib.pyplot (InternalHashError: 'Spines' object does not contain a 'name' spine) · Issue #3100 · streamlit/streamlit · GitHub

Taking from my linked answer, you can prevent hashing the Matplotlib objects and still have the output stored with:

import matplotlib
@st.cache(hash_funcs={matplotlib.figure.Figure: lambda _: None})
def mk_figure

There are some Matplotlib objects that contain a lot of objects (I suppose spines contain a list of points to display) so maybe you need to apply some specific hashing functions to those.

Hope it guides you :slight_smile:


Thank you very much for the pointer. I didn’t get that there is a GitHub repo. I didn’t see a link there on

No worries, here is actually the best place for this kind of questions :upside_down_face:

1 Like