How to 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_grid1 import 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_grid1 import 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_grid1 import 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.

Leave a Reply

Your email address will not be published. Required fields are marked *