Top label for matplotlib colorbars

Question:

By default matplotlib would position colorbar labels alongside the vertical colorbars. What is the best way to force the label to be on top of a colorbar? Currently my solution needs adjusting labelpad and y values depending on size of the label:

import numpy as np
import matplotlib.pylab as plt 

dat = np.random.randn(10,10)
plt.imshow(dat, interpolation='none')

clb = plt.colorbar()
clb.set_label('label', labelpad=-40, y=1.05, rotation=0)

plt.show()

colorbar top label

Is there a better, more generic way to do this?

Asked By: Vlas Sokolov

||

Answers:

You could set the title of the colorbar axis (which appears above the axis), rather than the label (which appears along the long axis). To access the colorbar’s Axes, you can use clb.ax. You can then use set_title, in the same way you can for any other Axes instance.

For example:

import numpy as np
import matplotlib.pylab as plt 

dat = np.random.randn(10,10)
plt.imshow(dat, interpolation='none')

clb = plt.colorbar()
clb.ax.set_title('This is a title')

plt.show()

enter image description here

Answered By: tmdavison
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.