Is it possible to change the font/background colour of a metric based on the value?

Pretty self explanatory title but as it says, is it possible to adjust the text colour of a metric in streamlit based on the value, ie. if the value is very high the text is Red or if it is very low it is green?

Similar to styling a dataframe except obviously I want to display my data in st.metric() format as opposed to using a dataframe, but would still like the visual cues.

I can use markdown and css to change the font colour but as far as I am aware, it would not be possible to apply this to only one specific metric, and would likely change the colour of every other metric on the screen.

Hi @AEB26B , you will have to:

  1. Define your number range of what constitutes High, Medium and Low (assuming you want these 3 categories)
  2. Use the hacky way to modify the colour of your metric widget based on your number value. (I used another way which can be seen in the thread: Style Column Metrics like the Documentation. You can repurpose this code for your benefit)

Cheers

Hi @Shawn_Pereira , appreciate the quick response.

I am not quite sure how this would work given that every single metric appears to have the same css class in the new version of streamlit, so I do not really see how you are able to apply different colours to different metrics?

(Apologies if I have misunderstood)

Does this mean the only possible way is to use the html string in your example?

Alex

The custom widget using the CSS is also very cool.

Would you be able to use these in columns?

Hi @AEB26B

In the link I have provided, in one of the earlier threads, I have provided multiple widgets (the code is for a single widget though).

You can put different widgets into columns via a function and address them how you wish.

Someone else in the same series of threads has addressed the problem using custom components.

You can use any method to achieve your goal.

Cheers

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