Home Â» How to Adjust the Position of a Matplotlib Colorbar

# 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')

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')

divider = make_axes_locatable(ax)
fig.colorbar(im, cax=cax, orientation='horizontal')

plt.show()```

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')