How can the position of a colorbar in Matplotlib be adjusted?

The position of a colorbar in Matplotlib can be adjusted by using the “location” parameter when creating the colorbar object. This parameter allows the user to specify the desired location of the colorbar, such as “top”, “bottom”, “left”, or “right” of the plot. Additionally, the “pad” parameter can be used to adjust the distance between the colorbar and the plot. These adjustments can be made by passing the appropriate values to the parameters, allowing for a customizable and visually appealing colorbar placement in Matplotlib.

Adjust the Position of a Matplotlib Colorbar


A colorbar is a bar that runs along the side of a Matplotlib chart and acts as a legend for the colors shown in the chart.

Matplotlib displays colorbars on the right side of a chart by default, but you can easily change this by using functions from the Matplotlib AxesGrid toolkit.

This tutorial shows several examples of how to use these functions in practice.

Example 1: Position Colorbar on Right Side of Chart

The following code shows how to generate a Matplotlib chart and how to place a colorbar on the right side of the chart:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1import make_axes_locatable

#make this example reproducible
np.random.seed(1)

#create chart
fig, ax = plt.subplots()
im = ax.imshow(np.random.rand(15,15))
ax.set_xlabel('x-axis label')

#add color bar
fig.colorbar(im)

plt.show()

Example 2: Position Colorbar Below Chart

The following code shows how to place a colorbar below a Matplotlib chart:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1import make_axes_locatable

#make this example reproducible
np.random.seed(1)

#create chart
fig, ax = plt.subplots()
im = ax.imshow(np.random.rand(15,15))
ax.set_xlabel('x-axis label')

#add color bar below chart
divider = make_axes_locatable(ax)
cax = divider.new_vertical(size='5%', pad=0.6, pack_start=True)
fig.add_axes(cax)
fig.colorbar(im, cax=cax, orientation='horizontal')

plt.show()

Position colorbar below Matplotlib chart

Note that the pad argument creates padding between the x-axis of the chart and the colorbar. The higher the value for pad, the further away the colorbar will be from the x-axis.

Example 3: Position Colorbar Above Chart

The following code shows how to place a colorbar above a Matplotlib chart:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1import make_axes_locatable

#make this example reproducible
np.random.seed(1)

#create chart
fig, ax = plt.subplots()
im = ax.imshow(np.random.rand(15,15))
ax.set_xlabel('x-axis label')

#add color bar below chart
divider = make_axes_locatable(ax)
cax = divider.new_vertical(size='5%', pad=0.4)
fig.add_axes(cax)
fig.colorbar(im, cax=cax, orientation='horizontal')

plt.show()

Matplotlib position colobar above chart

You can find more Matplotlib tutorials here.

x