# Coloured text in a table - conditional formatting

**URL:** <https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112>\
**Category:** Dash Python\
**Created:** [December 2, 2017, 4:49pm UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112 "2017-12-02T16:49:34Z")\
**Posts on this page:** 18\
**Page:** 1

<div class="post-metadata">

**Author:** ![Dee](https://avatars.discourse-cdn.com/v4/letter/d/58956e/32.png) [@Dee](https://community.plotly.com/u/Dee)\
**Post date:** [December 2, 2017, 4:49pm UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/1 "2017-12-02T16:49:34Z")

</div>

Good day guys  
I was experimenting with `from termcolor import colored`. The whole objective was to return a value in a certain color and be able to print it in a table. But then the unfortunate thing is I was returning the code of the color. I had created a table from a dataset from a csv file, the whole intention is for the table to highlight the changes in experimental data, with colour changes tracking the evolution of the values. I had set up a if function to iterate throught he dataset and colouring the output then appending it to a row, and this output would be in colour. For example  
`def colour(num):`  
`if float(num)\> 0:’  
‘return colored( num ,“red”)’  
‘if float(num)\<0:’  
'return colored(num,“green”)'  
ut what I returned was ‘[31m18.0[0m’ for the red value. Is there a way to add colour to a table entry. Had taken a look at [https://stackoverflow.com/questions/38511373/change-the-color-of-text-within-a-pandas-dataframe-html-table-python-using-style/38511805](https://stackoverflow.com/questions/38511373/change-the-color-of-text-within-a-pandas-dataframe-html-table-python-using-style/38511805) with the hope of using it to create a dataframe that can be printed as a table but then it returned an error. Is there a way to do such a task

---

<div class="post-metadata">

**Author:** ![nedned](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/nedned/32/8795_2.png) [@nedned](https://community.plotly.com/u/nedned)\
**Post date:** [December 3, 2017, 7:55am UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/2 "2017-12-03T07:55:49Z")

</div>

If you want to change the color of elements within the interface of your Dash app, then you need to use CSS styles, either inline, on the element in particular, or by attaching a style sheet to your app and giving your element you want targeted a className that you have a rule for in the style sheet.

The inline option is much simpler. You can do something like:

`html.Div("Some text", style={'color': 'red'})`

There are plenty of tutorials on how to use CSS styles to color various types of your HTML.

---

<div class="post-metadata">

**Author:** ![Dee](https://avatars.discourse-cdn.com/v4/letter/d/58956e/32.png) [@Dee](https://community.plotly.com/u/Dee)\
**Post date:** [December 3, 2017, 10:42am UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/3 "2017-12-03T10:42:15Z")

</div>

ok, interesting. The disadvantage is I am more of learning python as I go. Also CSS am like a new to it. So am thinking now where specifically I will put the style since the data is coming from a dataframe and befoe being output on the table it needs colour and will need to add a function to detect the ones that take different colours.

---

<div class="post-metadata">

**Author:** ![nedned](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/nedned/32/8795_2.png) [@nedned](https://community.plotly.com/u/nedned)\
**Post date:** [December 3, 2017, 11:22am UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/4 "2017-12-03T11:22:02Z")

</div>

If you’re constructing an updated layout fragment based on new data in a callback, then just add styles to the new layout being returned in the callback.

---

<div class="post-metadata">

**Author:** ![Dee](https://avatars.discourse-cdn.com/v4/letter/d/58956e/32.png) [@Dee](https://community.plotly.com/u/Dee)\
**Post date:** [December 3, 2017, 12:46pm UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/5 "2017-12-03T12:46:49Z")

</div>

What I did was that the table is generated from the dataframe, what updates is the dataframe, from there the table then plots the dataframe i.e consider the default table layout we have under [Dash Tutorial - Part 1: App Layout](https://plot.ly/dash/getting-started), all i did was create a function that updates the dataframe, then the rest will update automatically via a callback.

---

<div class="post-metadata">

**Author:** ![nedned](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/nedned/32/8795_2.png) [@nedned](https://community.plotly.com/u/nedned)\
**Post date:** [December 3, 2017, 1:06pm UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/6 "2017-12-03T13:06:31Z")

</div>

Is this the Dash DataTable component you’re using for a table or are you making your own out of [html.Tr](http://html.Tr) and html Td etc?

---

<div class="post-metadata">

**Author:** ![Dee](https://avatars.discourse-cdn.com/v4/letter/d/58956e/32.png) [@Dee](https://community.plotly.com/u/Dee)\
**Post date:** [December 3, 2017, 5:38pm UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/7 "2017-12-03T17:38:25Z")

</div>

Thats the component am using

---

<div class="post-metadata">

**Author:** ![chriddyp](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/chriddyp/32/16855_2.png) [@chriddyp](https://community.plotly.com/u/chriddyp)\
**Post date:** [December 4, 2017, 5:55pm UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/8 "2017-12-04T17:55:10Z")

</div>

> [@Dee](#):
>
> I was experimenting with from termcolor import colored.

@Dee - `termcolor` probably isn’t going to work here - the format of terminal colors (e.g. `31m18.0[0m`) is different than for those of HTML color.

> [@nedned](#):
>
> html.Div(“Some text”, style={‘color’: ‘red’})

This is the best way to do it. I recommend using `backgroundColor` too. Here is an example that is adapted from the HTML table explained in plot.ly/dash/getting-started

```auto
import dash
import dash_core_components as dcc
import dash_html_components as html

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(50, 4), columns=list('ABCD'))

COLORS = [
    {
        'background': '#fef0d9',
        'text': 'rgb(30, 30, 30)'
    },
    {
        'background': '#fdcc8a',
        'text': 'rgb(30, 30, 30)'
    },
    {
        'background': '#fc8d59',
        'text': 'rgb(30, 30, 30)'
    },
    {
        'background': '#d7301f',
        'text': 'white'
    },
]

def is_numeric(value):
    try:
        float(value)
        return True
    except ValueError:
        return False

def cell_style(value, min_value, max_value):
    style = {}
    if is_numeric(value):
        relative_value = (value - min_value) / (max_value - min_value)
        if relative_value <= 0.25:
            style = {
                'backgroundColor': COLORS[0]['background'],
                'color': COLORS[0]['text']
            }
        elif relative_value <= 0.5:
            style = {
                'backgroundColor': COLORS[1]['background'],
                'color': COLORS[1]['text']
            }
        elif relative_value <= 0.75:
            style = {
                'backgroundColor': COLORS[2]['background'],
                'color': COLORS[2]['text']
            }
        elif relative_value <= 1:
            style = {
                'backgroundColor': COLORS[3]['background'],
                'color': COLORS[3]['text']
            }
    return style

def generate_table(dataframe, max_rows=100):
    max_value = df.max(numeric_only=True).max()
    min_value = df.min(numeric_only=True).max()
    rows = []
    for i in range(min(len(dataframe), max_rows)):
        row = []
        for col in dataframe.columns:
            value = dataframe.iloc[i][col]
            style = cell_style(value, min_value, max_value)
            row.append(html.Td(value, style=style))
        rows.append(html.Tr(row))

    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in dataframe.columns])] +

        # Body
        rows)

app = dash.Dash()
app.css.append_css({
    "external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"
})

app.layout = html.Div(children=[
    generate_table(df)
])

if __name__ == ' __main__':
    app.run_server(debug=True)

```

 ![image](https://us1.discourse-cdn.com/flex024/uploads/plot/original/2X/b/b171131df0be68402fae399ae1a2979a43fb13c4.png)

---

<div class="post-metadata">

**Author:** ![Dee](https://avatars.discourse-cdn.com/v4/letter/d/58956e/32.png) [@Dee](https://community.plotly.com/u/Dee)\
**Post date:** [December 4, 2017, 6:55pm UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/9 "2017-12-04T18:55:52Z")

</div>

awesome stuff. Thanks.

---

<div class="post-metadata">

**Author:** ![nedned](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/nedned/32/8795_2.png) [@nedned](https://community.plotly.com/u/nedned)\
**Post date:** [December 4, 2017, 11:28pm UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/10 "2017-12-04T23:28:44Z")

</div>

Note though that this approach works for html components but not necessarily for other Dash components. So you won’t be able to style your `DataTable` in this way. It looks like this component doesn’t support any kind of style customisation at the moment. However the final table includes a number of descriptive classes such as `react-grid-Row` and `react-grid-Cell`, which you could target within your CSS stylesheet.

---

<div class="post-metadata">

**Author:** ![Dee](https://avatars.discourse-cdn.com/v4/letter/d/58956e/32.png) [@Dee](https://community.plotly.com/u/Dee)\
**Post date:** [January 14, 2018, 8:45pm UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/11 "2018-01-14T20:45:50Z")

</div>

The solution I found here was to identify the names of the columns I want to have colored texts, I then embedded an if loop into the generate table function specified by @chriddyp above, it was something like  
def generate\_table(dataframe, max\_rows=100):  
max\_value = df.max(numeric\_only=True).max()  
min\_value = df.min(numeric\_only=True).max()  
rows = []  
for i in range(min(len(dataframe), max\_rows)):  
row = []  
for col in dataframe.columns:  
value = dataframe.iloc[i][col]  
if col ==A:  
style = cell\_style(value, min\_value, max\_value)  
row.append([html.Td](http://html.Td)(value, style=style))  
else:  
style = cell\_style(value, min\_value, max\_value)  
row.append([html.Td](http://html.Td)(value, style=style))  
rows.append([html.Tr](http://html.Tr)(row))

```
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in dataframe.columns])] +

        # Body
        rows)

```

One will need to develop a custom function to generate the style they want for each cell, whether they are targeting the text or the backgound its all up to them.  
There was also an issue on up arrows and s=down arrows in a dataframe that I had opened but cant locate it, its solved using the same manner where one can store a black up or down Unicode arrow as an element of the dataframe and using the function there can target them using the colours they want to appear

---

<div class="post-metadata">

**Author:** ![tasselmi](https://avatars.discourse-cdn.com/v4/letter/t/9d8465/32.png) [@tasselmi](https://community.plotly.com/u/tasselmi)\
**Post date:** [July 20, 2018, 8:28pm UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/12 "2018-07-20T20:28:38Z")

</div>

Awesome！As a data analyst i am a fan of dash It’s so friendly to person who not a coder. Haha

---

<div class="post-metadata">

**Author:** ![monishaj93](https://avatars.discourse-cdn.com/v4/letter/m/50afbb/32.png) [@monishaj93](https://community.plotly.com/u/monishaj93)\
**Post date:** [March 28, 2019, 3:58am UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/13 "2019-03-28T03:58:10Z")

</div>

@nedned @chriddyp

This might be little off topic, I have a requirement, where in a text document, I need to highlight few key texts. These texts are selected from dropdowns. I am not able to comprehend how I will build such a html layout.

Any idea how should I go about it?

---

<div class="post-metadata">

**Author:** ![yezhang2019](https://avatars.discourse-cdn.com/v4/letter/y/779978/32.png) [@yezhang2019](https://community.plotly.com/u/yezhang2019)\
**Post date:** [December 2, 2019, 7:49pm UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/14 "2019-12-02T19:49:02Z")

</div>

I really liked this approach using html.table to color each cell. However, I also like the easy sort/filter function in dt.DataTable. Is there an easy way to add sort and filter in html.table?

---

<div class="post-metadata">

**Author:** ![Marc-Andre](https://avatars.discourse-cdn.com/v4/letter/m/e19b73/32.png) [@Marc-Andre](https://community.plotly.com/u/Marc-Andre)\
**Post date:** [December 3, 2019, 5:57pm UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/15 "2019-12-03T17:57:41Z")

</div>

This info about tables in this thread is a bit dated. The [DataTable](https://dash.plot.ly/datatable) supports [conditional formatting](https://dash.plot.ly/datatable/style) as well as sorting / filtering.

---

<div class="post-metadata">

**Author:** ![yezhang2019](https://avatars.discourse-cdn.com/v4/letter/y/779978/32.png) [@yezhang2019](https://community.plotly.com/u/yezhang2019)\
**Post date:** [December 3, 2019, 7:30pm UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/16 "2019-12-03T19:30:31Z")

</div>

Thanks for the information. I like the flexibility in html.table that enables you to assign color to each cell, which I don’t think the current DataTable supports. I am looking into package visdcc, which is a cool way to combine both coloring each cell and sorting/filtering together.

---

<div class="post-metadata">

**Author:** ![chriddyp](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/chriddyp/32/16855_2.png) [@chriddyp](https://community.plotly.com/u/chriddyp)\
**Post date:** [May 2, 2020, 1:15am UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/17 "2020-05-02T01:15:59Z")

</div>

(Reviving this since this old topic gets many views from Google! If you have a comment or question about this, please create a new thread):

I just published many recipes for coloring text within the table in the new [conditional formatting and colored text in a table documentation](https://dash.plotly.com/datatable/conditional-formatting). See the announcement here: [📣 DataTable Conditional Formatting Documentation](https://community.plotly.com/t/datatable-conditional-formatting-documentation/38763)

 ![image](https://us1.discourse-cdn.com/flex024/uploads/plot/original/2X/2/2ba41493fd1bb6d80a5d0ee62f4c5534d9a457a2.png)

Thanks for the feedback everyone, cheers!

---

<div class="post-metadata">

**Author:** ![chriddyp](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/chriddyp/32/16855_2.png) [@chriddyp](https://community.plotly.com/u/chriddyp)\
**Post date:** [May 2, 2020, 1:16am UTC](https://community.plotly.com/t/coloured-text-in-a-table-conditional-formatting/7112/18 "2020-05-02T01:16:03Z")

</div>


