4

I have pandas dataframe, and I would like to give a background gradient color based on absolute value.Imagine, my desire value is 6 in column A in the data frame. As number move from desire value, background gradient color changes on both directions same by absolute value (regardless to positive and negative direction).

The following post comes to close what I want, but these case color does not consider absolute value.pandas style background gradient both rows and columns,also pandas documentation http://pandas.pydata.org/pandas-docs/stable/user_guide/style.html

I have created minimum code:

import pandas as pd

colum1 = [-1,0,1,2,3,4,5,6,7,8,9,10,11,12]

df = pd.DataFrame(data=colum1,columns=["A"])

I have created expected output as image in the excel. I would like to get similar output from code. background gradient change by absolute valye

ahad pashayev
  • 43
  • 1
  • 7

1 Answers1

6

I faced with similar task, and after little 'research' i have found the solution.

from matplotlib import colors
import seaborn as sns

def b_g(s):
    cm=sns.light_palette("red", as_cmap=True)
    max_val = max(s.max(), abs(s.min()))
    norm = colors.Normalize(0,max_val)
    normed = norm(abs(s.values))
    c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cm)(normed)]
    return ['background-color: %s' % color for color in c]

The b_g function allows you to generate your custom colors_map based on your dataframe data and cm=sns.light_palette("red", as_cmap=True) could help to customize colors.

Applying of this function on a dataframe looks like:

dataframe.style.apply(b_g)

The trick here is in the using abs() function, when calculate normed values for data from a dataframe. Example result

Links on the documentation: https://seaborn.pydata.org/generated/seaborn.light_palette.html https://pandas.pydata.org/pandas-docs/version/0.18/style.html

Andrei
  • 76
  • 1
  • 4