Customise colour legend when formatting table

I want to colour a column by labelling extreme small and large values (in Red colour) and midpoint values (in Green colour).
The following is an example of colour scale legend.

However, by using the following code with default ‘RdYlGn’, I am only be able to do it with default colour legend

def discrete_background_color_bins(df, n_bins=7, columns='all'):

 bounds = [i * (1.0 / n_bins) for i in range(n_bins+1)]
 if columns == 'all':
     if 'id' in df:
         df_numeric_columns = df.select_dtypes('number').drop(['id'], axis=1)
     else:
         df_numeric_columns = df.select_dtypes('number')
 else:
     df_numeric_columns = df[columns]
 df_max = df_numeric_columns.max().max()
 df_min = df_numeric_columns.min().min()
 ranges = [
     ((df_max - df_min) * i) + df_min
     for i in bounds
 ]
 styles = []
 legend = []
 for i in range(1, len(bounds)):
     min_bound = ranges[i - 1]
     max_bound = ranges[i]
     backgroundColor = colorlover.scales[str(n_bins+4)]['div']['RdYlGn'][2:-2][i - 1]
     color = 'black'

     for column in df_numeric_columns:
         styles.append({
             'if': {
                 'filter_query': (
                     '{{{column}}} >= {min_bound}' +
                     (' && {{{column}}} < {max_bound}' if (i < len(bounds) - 1) else '')
                 ).format(column=column, min_bound=min_bound, max_bound=max_bound),
                 'column_id': column
             },
             'backgroundColor': backgroundColor,
             'color': color
         })
     legend.append(
         html.Div(style={'display': 'inline-block', 'width': '60px'}, children=[
             html.Div(
                 style={
                     'backgroundColor': backgroundColor,
                     'borderLeft': '1px rgb(50, 50, 50) solid',
                     'height': '10px'
                 }
             ),
             html.Small(round(min_bound, 2), style={'paddingLeft': '2px'})
         ])
     )

 return (styles, html.Div(legend, style={'padding': '5px 0 5px 0'}))

Can some one let me know how to highlight extreme values in Red and midpoint values in Green (or Blue) ?

Thanks.

This question is answered in this post: Flip/reverse colour legend when formatting table - #6 by AnnMarieW

1 Like

Thank you for the explanation. It is clear for me

Thanks again !!

1 Like