Search code examples
matplotlibstreamlit

Correct way to render a censusdis map in streamlit


I am attempting to build a streamlit app that facilitates explore US Census Data. I am using the censusdis package to get and render the data, and below is a snippet of my program that reproduces the problem:

import streamlit as st
import censusdis.data as ced
import censusdis.maps as cem
from censusdis.datasets import ACS5

df = ced.download(dataset=ACS5, 
                  vintage=2022, 
                  download_variables=['NAME', 'B19013_001E'], 
                  state='01',
                  county='*',
                  with_geometry=True)

st.dataframe(df[['NAME', 'B19013_001E']], hide_index=True)
cem.plot_map(df, 'B19013_001E', legend=True, with_background=True)
st.pyplot()

The code "works" but generates this warning:

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:

>>> fig, ax = plt.subplots()
>>> ax.scatter([1, 2, 3], [1, 2, 3])
>>>    ... other plotting actions ...
>>> st.pyplot(fig) 

I do not know how to fix this. I attempted to do:

st.pyplot(cem.plot_map(df, 'B19013_001E', legend=True, with_background=True))

But that generated this error (not warning):

AttributeError: 'Axes' object has no attribute 'savefig'

Solution

  • Just save the plot_map call as fig and then refer to fig.figure in st.pyplot.

    fig = cem.plot_map(df, 'B19013_001E', legend=True, with_background=True)
    st.pyplot(fig.figure)