Set Matplotlib colorbar size to match graph

08 Sep, 2021
Prerequisites: Matplotlib
Colorbar size that match graph or image is required to get good visualize effect. This can be achieved using any one of following approaches.
Fraction parameter in colorbar() is used to set the size of colorbar. Using this we can match colorbar size to graph as:
If vertical colorbar is used, then fraction=0.047 * (height_of_image / width_of_image)
If horizontal colorbar is used, then fraction=0.047 * (width_of_image / height_of_image)
Approach
Import module
Plot a graph
Set fraction parameter
Plot colorbar
Display plot
Example 1:
Python3
import matplotlib.pyplot as pltimport numpy as np # Plot an imagea = np.random.random((10, 20))plt.imshow(a, cmap='gray') # Calculate (height_of_image / width_of_image)im_ratio = a.shape[0]/a.shape[1] # Plot vertical colorbarplt.colorbar(fraction=0.047*im_ratio)plt.show()
Output:
Example 2:
Python3
import matplotlib.pyplot as pltimport numpy as np # Plot an imagea = np.random.random((10, 20))plt.imshow(a, cmap='gray') # Calculate (width_of_image/height_of_image)im_ratio = a.shape[1]/a.shape[0] # Plot horizontal colorbarplt.colorbar(orientation="horizontal", fraction=0.047*im_ratio)plt.show()
Output:
Axis_grid1 provides a helper function make_axes_locatable() which takes an existing axes instance and creates a divider for it. It provides append_axes() method that creates a new axes on the given side (“top”, “right”, “bottom” and “left”) of the original axes. 
Approach:
Import module
Plot image
Divide existing axes instance using make_axes_locatable()
Create new axes using append_axes()Use “top” or “bottom” side for horizontal colorbarUse “left” or “right” side for vertical colorbar
Use “top” or “bottom” side for horizontal colorbar
Use “left” or “right” side for vertical colorbar
Plot colorbar on created axis
Example 1:
Python3
import matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatableimport numpy as np # Plot image on axes axax = plt.gca()img = np.random.random((10, 20))im = plt.imshow(img, cmap='gray') # Divide existing axes and create new axes# at bottom side of imagedivider = make_axes_locatable(ax)cax = divider.append_axes("bottom", size="5%", pad=0.25) # Plot horizontal colorbarplt.colorbar(im, orientation="horizontal", cax=cax)plt.show()
Output:
Example 2:
Python3
import matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatableimport numpy as np # Plot image on axes axax = plt.gca()img = np.random.random((10, 20))im = plt.imshow(img, cmap='gray') # Divide existing axes and create# new axes at right side of imagedivider = make_axes_locatable(ax)cax = divider.append_axes("right", size="5%", pad=0.15) # Plot vertical colorbarplt.colorbar(im, cax=cax)plt.show()
Output:
Giving a colorbar its own axes using add_axes() method, can be an approach to get a colorbar matching given image.
Approach:
Plot a figure
Create axes using add_axes() method with position parameters:For vertical colorbar on right side of the image:left: Left point for colorbar=Right End position of imagebottom: Bottom point of colorbar= Bottom end position of imagewidth: Width of colorbarheight: Height of colorbar=Height of imageFor horizontal colorbar at bottom of the image:left: Left point for colorbar=Left End position of imagebottom: Bottom point of colorbar= Bottom end position of imagewidth: Width of colorbar =Width of imageheight: Height of colorbar
For vertical colorbar on right side of the image:left: Left point for colorbar=Right End position of imagebottom: Bottom point of colorbar= Bottom end position of imagewidth: Width of colorbarheight: Height of colorbar=Height of image
left: Left point for colorbar=Right End position of image
bottom: Bottom point of colorbar= Bottom end position of image
width: Width of colorbar
height: Height of colorbar=Height of image
For horizontal colorbar at bottom of the image:left: Left point for colorbar=Left End position of imagebottom: Bottom point of colorbar= Bottom end position of imagewidth: Width of colorbar =Width of imageheight: Height of colorbar
left: Left point for colorbar=Left End position of image
bottom: Bottom point of colorbar= Bottom end position of image
width: Width of colorbar =Width of image
height: Height of colorbar
Plot colorbar on created axes
Example 1 :
Python3
import matplotlib.pyplot as pltimport numpy as np # Plot imagefig = plt.figure()ax = plt.axes()img = np.random.random((10, 20))im = plt.imshow(img, cmap='gray') # Create new axes according to image positioncax = fig.add_axes([ax.get_position().x1+0.01,                    ax.get_position().y0,                    0.02,                    ax.get_position().height]) # Plot vertical colorbarplt.colorbar(im, cax=cax)plt.show()
Output:
Example 2:
Python3
import matplotlib.pyplot as pltimport numpy as np # Plot an imagefig = plt.figure()ax = plt.axes()img = np.random.random((10, 20))im = plt.imshow(img, cmap='gray') # Create new axes according to image positioncax = fig.add_axes([ax.get_position().x0,                    ax.get_position().y0-0.08,                    ax.get_position().width,                    0.02]) # Plot horizontal colorbar on created axesplt.colorbar(im, orientation="horizontal", cax=cax)plt.show()
Output:
anikakapoor
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
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python