How to Adjust the Position of a Matplotlib Colorbar?
Last Updated :
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)
Attribute | Description |
---|
cax | Axes into which the colorbar will be drawn. |
ax | Parent 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. |
colorbar | Use set_label to set the label to the colorbar |
pad | relative subplot gap or fraction of original axes between colorbar and new image axes |
LogNorm | Converting number arguments or color to RGBA |
figsize | 2-tuple of floats. Figure Dimension(width, height) in inches |
add_subplot | Add an Axes to the figure as part of a subplot arrangement |
add_axes | Present in figure module of matplotlib library used to add axes to figure |
imshow | The convention used in image processing: the origin is in the top left corner. |
pcolor | Creating a pseudocolor plot with a non-regular rectangular grid. |
Installation of Matplotlib colorbar
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 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 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 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 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 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 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 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 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:
Â
Â
Similar Reads
How to Adjust Title Position in Matplotlib?
In this article, you learn how to modify the Title position in matplotlib in Python. Method 1: Using matplotlib.pyplot.title() function The title() method in matplotlib module is used to specify title of the visualization depicted and displays the title using various attributes. Syntax: matplotlib.p
3 min read
How To Adjust Position of Axis Labels in Matplotlib?
Matplotlib is a powerful Python library for creating graphs and charts. By default, it places axis labels in standard positions, but sometimes you might want to move them for better readability or design. This article explains easy ways to adjust the position of axis labels in Matplotlib to make you
3 min read
Positioning the colorbar in Matplotlib
Matplotlib is a plotting library in Python programming language and it's by default numerical mathematics extension of NumPy library in python language. While programming in python language we use the matplotlib library package for graph and histogram visualizations. But while plotting histogram usi
3 min read
How to Change the Font Size of Colorbars in Matplotlib
Matplotlib is a powerful and widely used library in Python for data visualization. It offers a variety of plotting functions to create complex graphs and charts. One common visualization is a heatmap, which often includes a color bar to indicate the scale of values represented by colors. Adjusting t
4 min read
How to Change the Color of a Graph Plot in Matplotlib with Python?
Prerequisite: Matplotlib Python offers a wide range of libraries for plotting graphs and Matplotlib is one of them. Matplotlib is simple and easy to use a library that is used to create quality graphs. The pyplot library of matplotlib comprises commands and methods that makes matplotlib work like ma
2 min read
Python Plotly - How to set colorbar position for a choropleth map?
In this article, we will learn how to set colorbar position for a choropleth map in Python using Plotly. Color bar are gradients that go from bright to dark or the other way round. They are great for visualizing data that go from low to high, like income, temperature, or age. Choropleth maps are use
2 min read
How to Set Plot Background Color in Matplotlib?
Prerequisites:Â MatplotlibNumpyFrom the below figure one can infer that a plot consists of X-axis, Y-axis, plot title and the axes. By default, the color of the plot is white. If we have to set the background color of the plot so that our plot looks beautiful, we have to make the axes object, by usin
3 min read
Setting the Number of Ticks in plt.colorbar in Matplotlib?
Matplotlib is a powerful library for creating visualizations in Python. One of its features is the ability to add colorbars to plots, which can be customized in various ways. A common requirement is to set the number of ticks on a colorbar, especially when the default number of ticks leads to overla
5 min read
Imshow with two colorbars under Matplotlib
In this article, we will learn how to use Imshow with two colorbars under Matplotlib. Let's discuss some concepts : Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work wi
3 min read
How to Change the Size of Figures in Matplotlib?
Matplotlib provides a default figure size of 6.4 inches in width and 4.8 inches in height. While this is suitable for basic graphs, various situations may require resizing figures for better visualization, presentation or publication. This article explores multiple methods to adjust the figure size
3 min read