How to Adjust the Position of a Matplotlib Colorbar?

23 Nov, 2021
A colorbar is a bar that has various colors in it and is placed along the sides of the Matplotlib chart. It is the legend for colors shown in the chart. By default, the position of the Matplotlib color bar is on the right side. The position of the Matplotlib color bar can be changed according to our choice by using the functions from Matplotlib AxesGrid Toolkit. The placing of inset axes is similar to that of legend, the position is modified by providing location options concerning the parent box.
Syntax: fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)
To install the matplotlib colorbar directly execute the following command on Jupyter Notebook or Visual Studio Code to get the results, Matplotlib-colorbar package is installed in order to generate using the colorbar argument. Here, matplotlib.pyplot is used to create a colorbar in a simpler way.
pip install matplotlib-colorbar
Installation of Matplotlib Colorbar
Another way to create a colorbar using Matplotlib is by importing the matplotlib package and then creating the colorbar.
Python3
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm # specify dimensions of colorbar using random moduleZ = np.random.rand(5, 20) fig, ax0 = plt.subplots()ax0.pcolor(Z) ax0.set_title('Matplotlib-colorbar')plt.show()
Output:
Example 1: Position of Matplotlib colorbar on Right Side
Generating a matplotlib chart where the colorbar is positioned on the right side of the chart.
Python3
# Import packages necessary to create colorbarimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatable # make this example reproduciblenp.random.seed(2) #create chartfig, ax = plt.subplots()im = ax.imshow(np.random.rand(10,10))ax.set_xlabel('x-axis label') #add color barfig.colorbar(im) plt.show()
Output:
Example 2: Position of Matplotlib colorbar on Left
Generating a Matplotlib chart where the colorbar is positioned on the left of the chart. Here, the axes locations are set manually and the colorbar is linked to the existing plot axis using the keyword ‘location’. Location argument is used on color bars that reference multiple axes in a list, if you put your one axis in a list then the argument can be used here. 
Python3
#import matplotlib.pyplot to create chartimport matplotlib.pyplot as pltimport numpy as np #create subplotfig = plt.figure()ax = fig.add_subplot(111)axp = ax.imshow(np.random.randint(0, 10,( 10, 10)))ax.set_title('Colorbar on left') #adding colorbar and its positioncb = plt.colorbar(axp ,ax = [ax], location = 'left')plt.show()
  
Output:
 
 
This is a simple way to generate a colorbar and ensure it is on its own axis. Then the position of colorbar is specified using ‘cax’ parameter where axes are given for the color bar to be drawn.  
Python3
import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatable # make this example reproduciblenp.random.seed(1) # create chartfig = plt.figure()ax = fig.add_subplot(111)axp = ax.imshow(np.random.randint(0, 10, (10, 10)))ax.set_title('Colorbar on left') # Adding the colorbarcbaxes = fig.add_axes([0.1, 0.1, 0.03, 0.8])  # position for the colorbarcb = plt.colorbar(axp, cax = cbaxes)plt.show()
Output:
 
 
Example 3: Position of Matplotlib colorbar below the Chart
To position, the Matplotlib Colorbar below the chart then execute the following command, 
Python3
import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatable # make this reproduciblenp.random.seed(2) # create chartfig, ax = plt.subplots()im = ax.imshow(np.random.rand(10,10))ax.set_xlabel('x-axis label') # add color bar below chartdivider = make_axes_locatable(ax)cax = divider.new_vertical(size='5%', pad=0.6, pack_start = True)fig.add_axes(cax)fig.colorbar(im, cax = cax, orientation = 'horizontal') plt.show()
 Output: 
Pad argument creates padding between the x-axis of the chart and colorbar. Higher the value for the pad, the colorbar is away from the x-axis. To move colorbar relative to the subplot use the pad argument to fig.colorbar.
Python3
# import matplotlib packagesimport matplotlib.pyplot as pltimport numpy as np; np.random.seed(1)  # create chartfig, ax = plt.subplots(figsize=(4,4))im = ax.imshow(np.random.rand(11,16))ax.set_xlabel("x label") # pad argument to set colorbar away from x-axisfig.colorbar(im, orientation="horizontal", pad = 0.4)plt.show()
 Output:
 Use the instance of make_axes_locatable to divide axes and create new axes which are aligned to the image plot. Pad argument will allow setting space between two axes: 
Python3
# import matplotlib packagesimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatableimport numpy as np; np.random.seed(1) fig, ax = plt.subplots(figsize = (4,4))im = ax.imshow(np.random.rand(11,16))ax.set_xlabel("x label") # instance is used to divide axesdivider = make_axes_locatable(ax)cax = divider.new_vertical(size = "5%",                           pad = 0.7,                           pack_start = True)fig.add_axes(cax) # creating colorbarfig.colorbar(im, cax = cax, orientation = "horizontal") plt.show()
 Output:
 
Example 4: Position of Colorbar above Chart
To position, the Matplotlib Colorbar below the chart then execute the following command,
Python3
import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatable # make this example reproduciblenp.random.seed(1) # create chartfig, ax = plt.subplots()im = ax.imshow(np.random.rand(15, 15))ax.set_xlabel('x-axis label')ax.set_title('Colorbar above chart') # add color bar below chartdivider = make_axes_locatable(ax)cax = divider.new_vertical(size = '5%', pad = 0.5)fig.add_axes(cax)fig.colorbar(im, cax = cax, orientation = 'horizontal') plt.show()
 Output: 
 
ddeevviissaavviittaa
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list