Python dataviz: Seaborn heatmap palettes

Lately, I’ve been playing around with the Seaborn library and making heatmaps. The colors are usually some gradient showing highs and lows and I wanted to show how to make some of those here.

The heatmaps in Seaborn use hue values to assign colors. You can find out more about the different color palette types and options on their website, but here I’m using the cubehelix_palette() function to create a gradient between a light and dark color. Below is a sample plot in Jupyter Notebook generated in Jupyter Notebook followed by the source code.

import numpy as np
import seaborn as sns

for x in np.arange(start=0, stop=3, step=0.25):
    sns.palplot(sns.cubehelix_palette(n_colors=50, start=x, rot=0, light=0.7, dark=0))

ARGUMENTS

  • sns.palplot(): Utility function to plot out these palettes
  • n_colors: Specify the number of unique colors to use in the palette
  • start: The starting hue value
  • rot: The number of rotations to go about the hue wheel over the course of the palette
  • light: Between 0 and 1, the intensity of the lightest color (start value)
  • dark: Between 0 and 1, the intensity of the darkest color (final value)

EXPLANATION

As stated earlier, the cubehelix_palette() function is a palette where the lower numerical values are represented by both the lighter colors and starting hue values, and the higher numerical values are represented by both the darker colors and final hue values (based on the number of rotations about the hue wheel). In the example I show above, I set a rotation of rot=0, thus there is no rotation occurring, and, hence, the values are only represented by the light to dark intensity values.

Below is an example where I set the rotation to rot=4 just to see what happens.

for x in np.arange(start=0, stop=3, step=0.25):
    sns.palplot(sns.cubehelix_palette(n_colors=50, start=x, rot=4, light=0.7, dark=0))

Here you can see the hue value change over the palette because we’re telling it to rotate about the hue wheel 4 times. This is probably not that useful, especially for heatmaps. It would be too difficult to differentiate values this way.

For a greyscale palette:

sns.palplot(sns.cubehelix_palette(50, hue=0.05, rot=0, light=0.9, dark=0))

Here, we introduce the hue=0.05 argument, which controls the saturation of the hue colors. This argument takes a value from 0 to 1. Notice here the start argument is not specified — this doesn’t matter because we’re bringing the saturation argument down to nearly zero.

 

To use these palettes in practice, there is one more argument you will have to specify in the function: as_cmap=True. Below is an example of how to use the greyscale palette with a heatmap function call:

cmap = sns.cubehelix_palette(50, hue=0.05, rot=0, light=0.9, dark=0, as_cmap=True)
sns.heatmap(data, cmap=cmap)