Divergent background gradient setting the intermediate color to value "0"

183 views Asked by At

My goal is to get a df.style with background gradient going from red to white (intermediate color) to green. The thing is I want to set white color to the value 0. So, if we had a column with values like [1, 2, 3] the would all be green (in different intensities of course), if they were [-3, -2, 1] they would all be red. In resume, positive values will always be green, negative values always red and values very close to 0 will be close to white.

Here is an example of the initial code:

import pandas as pd
from  matplotlib.colors import LinearSegmentedColormap

df = pd.DataFrame({'A': [-3, -1, 1.5, 2, 100], 'B': [-3, -1, 1.5, 2, -100]})
cmap = LinearSegmentedColormap.from_list('rg', ["#FF3333", "#FFFFFF", "#39B241"], N = 255) 
df.style.background_gradient(cmap = cmap, axis = 0)

enter image description here

Columns "A" and "B" have outliers (one very large +++ and the other very ---), so in column A, for example, we get 1.5 and 2 with red color, which should not be allowed.

1

There are 1 answers

0
Quang Hoang On

Force your specific requirement with a function, don't use the gradient:

def color(s: pd.Series):
    colors = np.select([abs(s)<.1, s>0, s<0], ['white','green','red'])
    return [f'background-color:{c}' for c in colors]

df.style.apply(color)

Output:

enter image description here