How to put the colorbar below the figure in matplotlib ?

Example of how to put the colorbar below the figure in matplotlib

Horizontal colorbar in matplotlib

To put the colorbar horizontal and below the figure a solution is to use the argument orientation = "horizontal" in the matplotlib function matplotlib.pyplot.colorbar():

How to put the colorbar below the figure in matplotlib ? How to put the colorbar below the figure in matplotlib ?
How to put the colorbar below the figure in matplotlib ?

#!/usr/bin/env python

import matplotlib.pyplot as plt
import numpy as np

#----------------------------------------------------------------------------------------#

def f(x,y):
    return (x+y)*np.exp(-5.0*(x**2+y**2))

x,y = np.mgrid[-1:1:100j, -1:1:100j]

z = f(x,y)

#----------------------------------------------------------------------------------------#

plt.imshow(z,extent=[-1,1,-1,1])

plt.colorbar(orientation="horizontal")

plt.title("Colorbar bottom position \n with matplotib")

plt.savefig('colorbar_positioning_01.png', format='png', bbox_inches='tight')
plt.show()
plt.close()

Horizontal colorbar and same size as the figure in matplotlib

In addition, to have the horizontal colorbar with the same size as the figure, a solution is to use the function make_axes_locatable (see also How to have the colorbar with same size as the figure in matpltolib ?):

How to put the colorbar below the figure in matplotlib ?
How to put the colorbar below the figure in matplotlib ?

#!/usr/bin/env python

    from mpl_toolkits.axes_grid1 import make_axes_locatable

import matplotlib.pyplot as plt
import numpy as np

#----------------------------------------------------------------------------------------#

def f(x,y):
    return (x+y)*np.exp(-5.0*(x**2+y**2))

x,y = np.mgrid[-1:1:100j, -1:1:100j]

z = f(x,y)

#----------------------------------------------------------------------------------------#

fig, ax = plt.subplots(figsize=(4,4))

plt.title("Colorbar bottom position \n with matplotib")

im = plt.imshow(z,extent=[-1,1,-1,1])

divider = make_axes_locatable(ax)
cax = divider.new_vertical(size="5%", pad=0.5, pack_start=True)
fig.add_axes(cax)
fig.colorbar(im, cax=cax, orientation="horizontal")

plt.savefig('colorbar_positioning_03.png', format='png', bbox_inches='tight')
plt.show()
plt.close()

References

Image

of