How to use axes_grid1 toolkit to match graph In Python

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 colorbar
    • Use “left” or “right” side for vertical colorbar
  • Plot colorbar on created axis

Example 1:

Python3




import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
 
# Plot image on axes ax
ax = 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 image
divider = make_axes_locatable(ax)
cax = divider.append_axes("bottom", size="5%", pad=0.25)
 
# Plot horizontal colorbar
plt.colorbar(im, orientation="horizontal", cax=cax)
plt.show()


Output:

Set Matplotlib colorbar size to match graph

Example 2:

Python3




import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
 
# Plot image on axes ax
ax = 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 image
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.15)
 
# Plot vertical colorbar
plt.colorbar(im, cax=cax)
plt.show()


Output:

Set Matplotlib colorbar size to match graph

Set Matplotlib colorbar size to match graph

Colorbar size that match graph or image is required to get good visualize effect. This can be achieved using any one of following approaches.

Similar Reads

Use fraction parameter to match graph

Fraction parameter in colorbar() is used to set the size of colorbar in Python. Using this we can match colorbar size to graph as:...

Using axes_grid1 toolkit to match graph

...

Using add_axes() method to match graph

...

Contact Us