Skip to content Skip to sidebar Skip to footer

Seaborn Custom Range Heatmap

I need to build custom seaborn heatmap-like plot according to these requirements: import pandas as pd df = pd.DataFrame({'A': [0.3, 0.8, 1.3], 'B': [4, 9, 15],

Solution 1:

As far as I know, a heatmap can only have one scale of values. I would suggest normalizing the data you have in the df dataframe so the values in every column follow:

  • between 0 and 1 if the value is between df_info's minmax
  • below 0 if the value is below df_info's min
  • above 1 if the value is above df_info's max

To normalize your dataframe use :

for col in df:
    df[col] = (df[col] - df_info[col]['min']) / (df_info[col]['max'] - df_info[col]['min'])

Finally, to create the color-coded heatmap use :

import seaborn as sns
from matplotlib.colors import LinearSegmentedColormap

vmin = df.min().min()
vmax = df.max().max()

colors = [[0, 'darkblue'],
          [- vmin / (vmax - vmin), 'white'],
          [(1 - vmin)/ (vmax - vmin), 'white'],
          [1, 'darkred']]

cmap = LinearSegmentedColormap.from_list('', colors)
sns.heatmap(df, cmap=cmap, vmin=vmin, vmax=vmax)

The additional calculations with vmin and vmax allow a dynamic scaling of the colormap depending on the differences with the minimums and maximums.

Using your input dataframe we have the following heatmap: enter image description here

Post a Comment for "Seaborn Custom Range Heatmap"