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:

  • 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:

Here we are importing the required libraries and then plotting the graph, we are calculating the ratio then we are setting the fraction parameter and plotting the colorbar and finally displaying it.

Python3




import matplotlib.pyplot as plt
import numpy as np
 
# Plot an image
a = 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 colorbar
plt.colorbar(fraction=0.047*im_ratio)
plt.show()


Output:

Set Matplotlib colorbar size to match graph

Example 2:

Python3




import matplotlib.pyplot as plt
import numpy as np
 
# Plot an image
a = 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 colorbar
plt.colorbar(orientation="horizontal", fraction=0.047*im_ratio)
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