How to change the colorbar size of a seaborn heatmap figure in Python?
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)
- 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
- 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
Example 2: Increasing the size of the colorbar
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course