Skip to content
Related Articles

Related Articles

How to Adjust the Position of a Matplotlib Colorbar?
  • Last Updated : 09 Feb, 2021

A colorbar is a bar that has various colours in it and is placed along the sides of 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 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 with respect to the parent box.

Syntax: fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)

AttributeDescription
caxAxes into which the colorbar will be drawn.
axParent axes from which space for a new colorbar axes are stolen. If a list of axes is given they are resized to make room for colorbar axes.
colorbarUse set_label to set the label to the colorbar
padrelative subplot gap or fraction of original axes between colorbar and new image axes
LogNormConverting number arguments or color to RGBA
figsize2-tuple of floats. Figure Dimension(width, height) in inches
add_subplotAdd an Axes to the figure as part of a subplot arrangement
add_axesPresent in figure module of matplotlib library used to add axes to figure
imshowThe convention used in image processing: the origin is in the top left corner. 
pcolorCreating a pseudocolor plot with a non-regular rectangular grid.

Installation of Matplotlib colorbar

To install 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 create the colorbar.

Python3






# Implementation of matplotlib function 
import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.colors import LogNorm 
  
# specify dimensions of colorbar using random module
Z = 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 colorbar
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
  
# make this example reproducible
np.random.seed(2)
  
#create chart
fig, ax = plt.subplots()
im = ax.imshow(np.random.rand(10,10))
ax.set_xlabel('x-axis label')
  
#add color bar
fig.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 existing plot axis using the keyword ‘location’. Location argument is used on color bars which 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 chart
import matplotlib.pyplot as plt
import numpy as np
  
#create subplot
fig = 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 position
cb = plt.colorbar(axp ,ax = [ax], location = 'left')
plt.show()

Output:

This is a simple way to generate colorbar and ensuring 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 np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
  
# make this example reproducible
np.random.seed(1)
  
# create chart
fig = 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 colorbar
cbaxes = fig.add_axes([0.1, 0.1, 0.03, 0.8])  
  
# position for the colorbar
cb = 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 np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
  
# make this reproducible
np.random.seed(2)
  
# create chart
fig, ax = plt.subplots()
im = ax.imshow(np.random.rand(10,10))
ax.set_xlabel('x-axis label')
  
# add color bar below chart
divider = 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 pad, the colorbar is away from the x-axis. To move colorbar relative to the subplot use pad argument to fig.colorbar.

Python3




# import matplotlib packages
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
  
  
# create chart
fig, 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-axis
fig.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 packages
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import 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 axes
divider = make_axes_locatable(ax)
cax = divider.new_vertical(size = "5%",
                           pad = 0.7,
                           pack_start = True)
fig.add_axes(cax)
  
# creating colorbar
fig.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 the command,

Python3




import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
  
# make this example reproducible
np.random.seed(1)
  
# create chart
fig, 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 chart
divider = 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:


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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :