How to use add_axes() method to match graph In Python
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 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 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 plt import numpy as np # Plot image fig = plt.figure() ax = plt.axes() img = np.random.random(( 10 , 20 )) im = plt.imshow(img, cmap = 'gray' ) # Create new axes according to image position cax = fig.add_axes([ax.get_position().x1 + 0.01 , ax.get_position().y0, 0.02 , ax.get_position().height]) # Plot vertical colorbar plt.colorbar(im, cax = cax) plt.show() |
Output:
Example 2:
Python3
import matplotlib.pyplot as plt import numpy as np # Plot an image fig = plt.figure() ax = plt.axes() img = np.random.random(( 10 , 20 )) im = plt.imshow(img, cmap = 'gray' ) # Create new axes according to image position cax = fig.add_axes([ax.get_position().x0, ax.get_position().y0 - 0.08 , ax.get_position().width, 0.02 ]) # Plot horizontal colorbar on created axes plt.colorbar(im, orientation = "horizontal" , cax = cax) plt.show() |
Output:
Prerequisites: Matplotlib
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.