Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Top label for matplotlib colorbars

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?

like image 277
Vlas Sokolov Avatar asked Nov 16 '15 14:11

Vlas Sokolov


People also ask

How do I name a Colorbar in Matplotlib?

Steps. Create random data using numpy. Use imshow() method to represent data into an image, with colormap "PuBuGn" and interpolation= "nearest". Set the title on the ax (of colorbar) using set_title() method.

What is CMAP =' viridis?

( cmaps.viridis is a matplotlib.colors.ListedColormap ) import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import colormaps as cmaps img=mpimg.imread('stinkbug.png') lum_img = np.flipud(img[:,:,0]) imgplot = plt.pcolormesh(lum_img, cmap=cmaps.viridis)

How do you add a Colorbar in Python?

To make colorbar orientation horizontal in Python, we can use orientation="horizontal" in the argument.

How do I change the location of my color bar?

To move the colorbar to a different tile, set the Layout property of the colorbar. To display the colorbar in a location that does not appear in the table, use the Position property to specify a custom location. If you set the Position property, then MATLAB sets the Location property to 'manual' .


1 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

like image 125
tmdavison Avatar answered Oct 06 '22 00:10

tmdavison