Sunday, November 17, 2024
Google search engine
HomeLanguagesHow to change the colorbar size of a seaborn heatmap figure in...

How to change the colorbar size of a seaborn heatmap figure in Python?

Prerequisites: Seaborn

A colorbar is a rectangular color scale that is used to interpret the data of a heatmap. By default, it is of the same size as the heatmap but its size can be changed using the cbar_kws parameter of the heatmap() function. This parameter accepts dictionary type values and to change the size of the colorbar, its shrink parameter needs to be accordingly. By default, it is 1, which makes the colorbar of the same size as the heatmap. To make the colorbar small, shrink should be given a value smaller than 1 and to increase its size it should be given a value greater than 1.

Syntax of heatmap():

Syntax: seaborn.heatmap(data, *, vmin=None, vmax=None, cmap=None, center=None, annot_kws=None, linewidths=0, linecolor=’white’, cbar=True, **kwargs)

Important Parameters:

  • data: 2D dataset that can be coerced into an ndarray.
  • vmin, vmax: Values to anchor the colormap, otherwise they are inferred from the data and other keyword arguments.
  • cmap: The mapping from data values to color space.
  • center: The value at which to center the colormap when plotting divergent data.
  • annot: If True, write the data value in each cell.
  • fmt: String formatting code to use when adding annotations.
  • linewidths: Width of the lines that will divide each cell.
  • linecolor: Color of the lines that will divide each cell.
  • cbar: Whether to draw a colorbar.

All the parameters except data are optional.

Returns: An object of type matplotlib.axes._subplots.AxesSubplot 

Approach 

  • Import modules
  • Load or create data
  • Create a heatmap using appropriate values, within this function itself, set cbar_kws with shrink and its required value.
  • Display plot

Implementation using this approach is given below:

Database in use: Bestsellers

Example 1: Decreasing the size of the colorbar

Python3




# import modules
import matplotlib.pyplot as mp
import pandas as pd
import seaborn as sb
  
# load data
data = pd.read_csv("bestsellers.csv")
  
# plotting heatmap
sb.heatmap(data.corr(), annot=None, cbar_kws={'shrink': 0.6})
  
# displaying heatmap
mp.show()


Output:

Example 2: Increasing the size of the colorbar

Python3




# import modules
import matplotlib.pyplot as mp
import pandas as pd
import seaborn as sb
  
# load data
data = pd.read_csv("bestsellers.csv")
  
# plotting heatmap
sb.heatmap(data.corr(), annot=None, cbar_kws={'shrink': 1.3})
  
# displaying heatmap
mp.show()


Output:

RELATED ARTICLES

Most Popular

Recent Comments