All About Heatmaps
By: Shrashti Singhal
Tags: Analytics, Visualization, Python, Heatmap, Seaborn

18. Customizing Heatmap Style

i. vmin & vmax

Parameters vmin & vmax are used to change the colormap's limits, which adjust the lower and upper contrast bounds. Everything below vmin and everything above vmax will be of the same colors, respectively.

vmin and vmax are set to lie outside of the range of the data for a washed-out look.

sns.heatmap(data.corr(), vmin=-0.2, vmax= 0.2)

Customization using vmin & vmax (Image by the Author)

ii. Cmap

cmap values are set to change the default colormap value.

sns.heatmap(data.corr(), cmap=”coolwarm”)

Customization using camp (Image by the Author)

iii. center

Data is centered on ‘0’ on a default colormap. The center can be changed by setting the ‘center’ parameter of the colormap to a specific value.

sns.heatmap(data.corr(), cmap=”coolwarm”, center=0.6)

Customization using center (Image by the Author)

iv. Robust

Robust remove vmin or vmax using sns.heatmap() robust parameter. The ‘robust’ works like an “auto-contrast” for choosing good values by fixing contrast levels based on quartiles.

sns.heatmap(data.corr(), cmap=”coolwarm”, robust=True)

Customization using robust (Image by the Author)

v. Annot

Annot parameter fills the cells with the relative correlation coefficient, which ranges from -1 to 1.

sns.heatmap(data.corr(), cmap=”coolwarm”, annot=True)

Customization using annot (Image by the Author)

vi. Fmt

The ‘annot’ only adds numeric value on the python heatmap cell, but the ‘fmt’ parameter allows us to change these annotations' format and significantly add string (text) values. For string values, ‘annot’ should contain an array of strings, and ‘fmt’ should be ‘s.’

The default scientific notation is 2g. Fmt accepts the below values:

s - string

f, F – fixed point

g, G - general format

e, E - exponent format

Annotate with the numeric value:

sns.heatmap (data.corr(), cmap=’coolwarm’, annot=True, fmt=”.3f”)

Customization using fmt- numeric values (Image by the Author)

data2=(data.corr()).round(3)

corrA = np.squeeze(np.asarray(data2))

print(corrA)

rows, cols = (12, 12)

arr_annot = [[(str(corrA[j][i])+’_’+str(j)+’_’+str(i)) for i in range(cols)] for j in range(rows)]

sns.heatmap(data.corr(), cmap=’coolwarm’,annot = arr_annot, fmt=”s”)

Customization using fmt- string values (Image by the Author)

vii. annot_kws

Sometimes annot and fmt parameter is not sufficient to generate a meaningful and stylish Heatmap. For formatting of cell annotations, such as the font size, font color, font orientation, etc., can be done by annot_kws. The ‘annot_kws’ means annotate keyword arguments, which help change the style and formatting of annotating text.

The ‘annot_kws’ accepts all ‘ax.text’ or ‘matplotlib.text’ arguments. For passing annot_kws, then annot value must be True.⁷

· annot_kws: values as a dictionary of the key, value mappings, optional

· fontsize: The size of the font

· fontstyle: The style of font like italic, oblique and normal

· fontfamily: a family of font like serif, cursive

· color: the color of the font

· alpha: transparency of the text

· rotation: the rotation of the text

· verticalalignment: vertical alignment (center, top, bottom, baseline, center_baseline)

· backgroundcolor: Background color of the text sns.heatmap(data.corr(), cmap=”coolwarm”, annot=True, annot_kws={‘fontsize’:12, ‘fontstyle’:’italic’, ‘color’:”b”, ‘alpha’:0.6, ‘rotation’:”vertical”,’verticalalignment’:’center’, ‘backgroundcolor’:’w’})

Customization using annot_kws (Image by the Author)

viii. Linewidth

Increase or decrease line width between each cell by the ‘linewidth’ parameter.

sns.heatmap(data.corr(), cmap=”coolwarm”, linewidth=0.5)

Customization using linewidth (Image by the Author)

ix. Linecolor

Sometimes the ‘linewidth’ parameter fails to divide the heatmap cell because of color complexity. The ‘linecolor’ parameter gives the flexibility to choose any color for the heatmap line. The ‘linewidth’ parameter is mandatory to set the ‘linecolor.’ For the list of colors, refer to the following document.

sns.heatmap(data.corr(), cmap=”coolwarm”, linewidth=0.5, linecolor=’g’)

Customization using linecolor (Image by the Author)

x. CBAR

The legend or ‘cbar’ is visible by default. It doesn’t make much sense of heatmap without the key. Still, if the key is not needed, ‘cbar’ is set to ‘False.’

sns.heatmap(data.corr(), cmap=”coolwarm”, cbar=False)

Customization using cbar (Image by the Author)

xi. Cbar_kws

The color bar keyword arguments (cbar_kws) parameter can accept multiple keyword arguments as a dictionary. The ‘cbar_kws’ accepts all matplotlib color bar parameters.⁷

· orientation: the direction of the color bar, ‘horizontal’ or ‘vertical.’

· shrink: the size of the color bar

· extend: extend used to taper the color bar. Values are ‘both, ‘min, ‘max,’ and ‘neither’ depending upon the requirement.

· extendfrac: ‘extendfrac’ is used to adjust the extension of the color bar. ‘False’ value for no pointer, ‘auto’ value adjust pointer automatically, and float value to adjust the color bar pointer manually.

· ticks: The ‘ticks’ parameter is used to change the color bar’s ticks; the value can be a list or numpy array of ticks

· drawedges: For edges on the color bar. Value is Boolean. ‘True’ for edges, ‘False’ for no edges. sns.heatmap(data.corr(), cmap=”coolwarm”, cbar_kws={“label”:”Wine Quality Colorbar”, “orientation”:”horizontal”, “shrink”:1, ‘extend’:’both’, ‘extendfrac’:0.1, “ticks”:np.arange(0,3), “drawedges”:True })

Customization using cbar_kws (Image by the Author)

xii. ax and cbar_ax

ax and cbar_ax are used to plot heatmap and cbar on separate axes.

f, (ax, cbar_ax) = plt.subplots(1,2, figsize=(15,12), gridspec_kw={“wspace”:0.05, “width_ratios”:(0.8,0.1)} )

ax = sns.heatmap(data.corr(), cmap=’coolwarm’, ax=ax, cbar_ax=cbar_ax)

Customization using ax and cbar_ax (Image by the Author)

The ‘ax’ is also used to set various axes level functions such as title, x label, y label, etc.

f, (ax, cbar_ax) = plt.subplots(1,2, figsize=(15,12), gridspec_kw={“wspace”:0.05, “width_ratios”:(0.8,0.1)} )

sns.heatmap(data.corr(), cmap=’coolwarm’, ax=ax,cbar_ax=cbar_ax)

ax.set(title=”Wine Quality Heatmap”,

xlabel=”Feature Rows”,

ylabel=”Feature Columns”)

Customization using ax for implementing axes level functions (Image by the Author)

xiii. Square

‘square’ parameter is used to shape the Heatmap cells as squares. The ‘square’ forces the aspect ratio of the blocks to be equal.

sns.heatmap(data.corr(), cmap=”coolwarm”, square=True)

Customization using square (Image by the Author)

xiv. xticklabel & yticklabel

To set the labels on X-axis and Y-axis, ‘xticklabel’ and ‘yticklabel’ parameters are used.⁷

xticklabel: To place tags on the x-axis of heatmap. ‘xticklabels’ is an optional parameter that accepts arguments as “auto,” bool, list-like, numpy array, or int. False: to hide the labels Array/list/int: to set values, other than default sns.heatmap(data.corr(),cmap=”coolwarm”,xticklabels = np.arange(0,12))

Customization using xticklabel & yticklabel (Image by the Author)

Rotation of label ticks is possible by using the ‘rotation’ parameter.

To rotate the default labels, ‘get_yticklabels()’ or ‘get_xticklabels()’ is used to get the default labels, then rotation is set to an angle value.

HM=sns.heatmap(data.corr(), cmap=”coolwarm”) HM.set_yticklabels(HM.get_yticklabels(), rotation=40)

Customization using rotation with xticklabel & yticklabel (Image by the Author)

xv. mask

The entire heatmap can be divided into two triangles, the upper triangle and the lower triangle. Both the triangle provides a complete set of information alone. Therefore it is redundant to plot the entire heatmap. It is preferred to plot either of the triangles.

To mask the upper triangle, ‘triu,’ a numPy method is used. To hide the lower triangle, ‘tril,’ a numPy method is used.

sns.heatmap(data.corr(),cmap=”coolwarm”,mask= np.triu(data.corr()))

Heatmap by masking upper triangle (Image by the Author)

To hide specific values, the condition to hide the desired values is passed in the ‘mask’ parameter. Here, we are masking every alternate row starting from row 1 and every alternate column starting from column 0.

mask = np.zeros(data.corr().shape) mask[1::2,0::2] = 1 sns.heatmap(data.corr(), annot=True,cmap=”coolwarm”,mask= mask )

Customization using a binary mask (Image by the Author)

Masking the negatively correlated data

data1=(data.corr()).round(3) corrA = np.squeeze(np.asarray(data1)) mask = np.zeros(data.corr().shape) for i in range(12): for j in range(12): if corrA[i][j]<0: mask[i][j]=1 plt.figure(figsize=(15,12)) sns.heatmap(data.corr(), annot=True,cmap=”coolwarm”,mask= mask )

Customization using a conditional mask (Image by the Author)

xvi. kwargs

The ‘kwargs’ is used to pass other keyword arguments, generally not available in seaborn such as rasterized, edge color, cap-style, etc. It allows all keyword arguments of matplotlib ‘ax.pcolormesh.’

Kwargs accepts a dictionary as an argument.

kwargs = {‘alpha’:.9,’linewidth’:3, ‘linestyle’:’ — ‘, ‘linecolor’:’k’,’rasterized’:False, ‘edgecolor’:’w’, “capstyle”:’projecting’,} sns.heatmap(data.corr(), cmap=”coolwarm”, **kwargs )

Customization using kwargs (Image by the Author)

xvii. Controlling aesthetics of the entire heatmap by set_theme

seaborn.set_theme(context='notebook', style='darkgrid', palette='deep', font='sans-serif', font_scale=1, color_codes=True, rc=None)¹²

Seaborn figure Style

The set_style() interface can be used for manipulating the styles. It helps to set the theme of the plot. There are five themes available:

Darkgrid

Whitegrid

Dark

White

Ticks

The default theme is darkgrid.

Removing axes spine

The top and right axis spines can be removed using the despine() function in the white and ticks themes.

Scaling Plot Elements

The Heatmap scale can be controlled by using the set_context() function or set_theme() function. Based on relative size, there are four pre-set templates for contexts:

Paper

Notebook

Talk

Poster

By default, the context is the notebook.

Font Size of all Seaborn components

The font size of all the seaborn components can be changed using Seaborn's ‘font_scale’ attribute. The default scale is ‘1’.

sns.set_theme(context=’paper’, style=’ticks’,font_scale=2) sns.heatmap(data.corr()) sns.despine()

Customization using set_theme() & despine() (Image by the Author)

xviii. Seaborn heatmap subplots: Create multiple heatmaps

Multiple Heatmaps can be generated using the matplotlib plt.subplot() function.

plt.subplot(1,3,1)

sns.heatmap(data.corr(), cbar=False, linecolor=”w”, linewidths=1) plt.subplot(1,3,2)

sns.heatmap(data=data[[‘quality’,’alcohol’]].corr(), cmap=’inferno’) plt.subplot(1,3,3)

sns.heatmap(data.corr(), cmap=”coolwarm”,mask= np.tril(data.corr()), cbar=False )

Multiple Heatmaps by subplot() (Image by the Author)

Finalize

sns.set_theme(context=’paper’, style=’ticks’,font_scale=2) f, (ax, cbar_ax) = plt.subplots(1,2, figsize=(15,12), gridspec_kw={“wspace”:0.05, “width_ratios”:(0.8,0.05)} ) mask = np.triu(data.corr()) annot_kws={‘fontsize’:14, ‘fontstyle’:’italic’,’fontweight’:’bold’, ‘color’:”k”, ‘alpha’:0.6, ‘rotation’:None,’verticalalignment’:’center’, ‘backgroundcolor’:’None’} cbar_kws={“label”:”Wine Quality Colorbar”,”orientation”:”vertical”, “shrink”:1,’extend’:’max’, ‘ticks’:[-0.8, -0.5,0, 0.5], ‘extendfrac’:0.1, “drawedges”:True } sns.heatmap(data.corr(), vmin=None, vmax=0.7, cmap=’BuGn’, center=None, robust=True, annot=True, fmt=’.2F’, annot_kws=annot_kws, linewidths=0.8, linecolor=’white’, cbar=True, cbar_kws=cbar_kws, cbar_ax=cbar_ax, square=True, xticklabels=’auto’, yticklabels=’auto’, mask=mask, ax=ax) f.suptitle(“Wine Quality Heatmap”, fontsize=24, fontweight=’bold’) ax.set(xlabel=”Feature Rows”, ylabel=”Feature Columns”)