Isn't streamlit able to apply df.style.background_gradient?

Summary

I have a dataframe with backgruond_gradient coloring that works just fine in VSC or Jupyter Notebook, but when I use st.dataframe(…), streamlit applys the cmap but without taking into account the additional arguments. Is there a workaround, og am I misunderstanding something?

Also, a bit off topic, but having multiple dataframes on the streamlit page, is it possible to set a fixed width for index column, so that the st.dataframes are more aligned?

thank you.

Steps to reproduce

Code snippet:

cmap = plt.cm.get_cmap('RdYlGn')
ldf.style.background_gradient(cmap=cmap,vmin=(-0.015),vmax=0.015,axis=None).format('{:.2%}')

st.dataframe(ldf.style.background_gradient(cmap=cmap,vmin=(-0.015),vmax=0.015,axis=None).format('{:.2%}'))

Expected behavior:

if I run ldf in IDE I get (as it is supposed to be):
Annotation 2023-05-11 105155

Actual behavior:

However, when I run streamlit line i get:.

Debug info

  • Streamlit version: 1.20.0
  • Python version: 3.11.0
  • Using Conda 23.1.0
  • OS version: MS windows 10, Enterprise, 10.0.19044
  • Browser version: Microsoft Edge 112.0.1722.48 (Official build) (64-bit)

Officially, styler support is still experimental and limited. That being said, I get the same colors using that cmap whether sending the styler to st.dataframe or converting it to html and rendering it directly.

import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({
    'A':[.0074,.0049,.0023,.0021],
    'B':[.0018,.0034,.0008,.0013],
    'C':[.0057,.0034,.0008,.0007]
})

cmap = plt.cm.get_cmap('RdYlGn')
st.dataframe(df.style.background_gradient(cmap=cmap,vmin=(-0.015),vmax=0.015,axis=None))

st.write(df.style.background_gradient(cmap=cmap,vmin=(-0.015),vmax=0.015,axis=None).to_html(), unsafe_allow_html=True)

image

To double check, can you apply the .to_html() method to your styler and render in directly to confirm? If you find there is a discrepency, can you try a different version of Streamlit. I was running Streamlit 1.22 on Python 3.10.11. Matplot lib was version 3.7.1 also.

Thank you very much for the solution. It solved the issue :slight_smile:

1 Like

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