Skip to main content

How to adjust a colorbar in Python

Color bars in matplotlib

In this post I will show how to adjust the color bars to look nice next to an image.

In [1]:
## importing libraries
import pyfits
import matplotlib.pyplot as plt
import numpy as np
import pylab
In [40]:
## loading data with pyfits
p = '/home/fatima/Desktop/my_papers/paper_1/images/'
sufi_214 = pyfits.getdata(p+'flip_cont.fits')
fig = plt.figure(figsize=(10,10)) #defining the figure with the figure size (widthxheight)
ax = fig.add_subplot(1,1,1)  #one way to add subplots (nrows, ncols, index)
ax.imshow(sufi_214,cmap='gray')
Out[40]:
<matplotlib.image.AxesImage at 0x7fb13cf12110>

If we want to add a colorbar, we can use the following:

In [31]:
from matplotlib import cm
plt.clf()
fig = plt.figure(figsize=(10,10)) 
ax = fig.add_subplot(1,1,1)  
im = ax.imshow(sufi_214,cmap='gray')
fig.colorbar(im,ax=ax,orientation='vertical')
#ax.set_aspect('auto')
Out[31]:
<matplotlib.colorbar.Colorbar at 0x7fb13d16a1d0>
<matplotlib.figure.Figure at 0x7fb13e006690>

As you can see, the length of the color bar exceeds that of the image, and it does not look very nice. The way to solve this is to divide the axis in which the image is plotted and assign a part of it to the colorbar.

In [32]:
from mpl_toolkits.axes_grid1 import make_axes_locatable, axes_size
In [39]:
plt.clf()
fig = plt.figure(figsize=(10,10)) 
ax = fig.add_subplot(1,1,1)  
im = ax.imshow(sufi_214,cmap='gray')
divider = make_axes_locatable(ax)
cax = divider.append_axes('right',pad=0.05,size=0.15) #size is the width of the color bar and pad is the fraction of the new axis
fig.colorbar(im,cax=cax)
Out[39]:
<matplotlib.colorbar.Colorbar at 0x7fb13cd1ed90>
<matplotlib.figure.Figure at 0x7fb13cd86a90>

Now the color bar looks nicer