How to set Matplotlib color bar size to match graph with Python?

Sometimes, we want to set Matplotlib color bar size to match graph with Python.

In this article, we’ll look at how to set Matplotlib color bar size to match graph with Python.

How to set Matplotlib color bar size to match graph with Python?

To set Matplotlib color bar size to match graph with Python, we can use the make_axes_locatable function.

For instance, we write

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
    
plt.figure()
ax = plt.gca()
im = ax.imshow(np.arange(100).reshape((10,10)))
    
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
   
plt.colorbar(im, cax=cax)

to call make_axes_locatable to create an axes on the right side of ax.

Then we call append_axes with 'right' to append axes to the right of the graph.

Also, we set the width of the axis to 5% by setting the size to '5%'.

And we add 0.05 inch of padding by setting pad to 0.05.

Conclusion

To set Matplotlib color bar size to match graph with Python, we can use the make_axes_locatable function.