Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a matplotlib colorbar extents?

I'd like to display a colorbar representing an image's raw values along side a matplotlib imshow subplot which displays that image, normalized.

I've been able to draw the image and a colorbar successfully like this, but the colorbar min and max values represent the normalized (0,1) image instead of the raw (0,99) image.

f = plt.figure()
# create toy image
im = np.ones((100,100))
for x in range(100):
    im[x] = x
# create imshow subplot
ax = f.add_subplot(111)
result = ax.imshow(im / im.max())

# Create the colorbar
axc, kw = matplotlib.colorbar.make_axes(ax)
cb = matplotlib.colorbar.Colorbar(axc, result)

# Set the colorbar
result.colorbar = cb

If someone has a better mastery of the colorbar API, I'd love to hear from you.

Thanks! Adam

like image 950
Adam Fraser Avatar asked Feb 28 '23 07:02

Adam Fraser


2 Answers

It looks like you passed the wrong object to the colorbar constructor.

This should work:

# make namespace explicit
from matplotlib import pyplot as PLT

cbar = fig.colorbar(result)

The snippet above is based on the code in your answer; here's a complete, stand-alone example:

import numpy as NP
from matplotlib import pyplot as PLT

A = NP.random.random_integers(0, 10, 100).reshape(10, 10)
fig = PLT.figure()
ax1 = fig.add_subplot(111)

cax = ax1.imshow(A, interpolation="nearest")

# set the tickmarks *if* you want cutom (ie, arbitrary) tick labels:
cbar = fig.colorbar(cax, ticks=[0, 5, 10])

# note: 'ax' is not the same as the 'axis' instance created by calling 'add_subplot'
# the latter instance i bound to the variable 'ax1' to avoid confusing the two
cbar.ax.set_yticklabels(["lo", "med", "hi"])

PLT.show()

As i suggested in the comment above, i would choose a cleaner namespace that what you have--e.g., there are modules with the same name in both NumPy and Matplotlib.

In particular, i would use this import statement to import Matplotlib's "core" plotting functionality:

from matplotlib import pyplot as PLT

Of course, this does not get the entire matplotlib namespace (which is really the point of this import statement) though this is usually all that you'll need.

like image 69
doug Avatar answered Mar 02 '23 08:03

doug


I know that it might be too late, but...
For me replacing in the last line of Adam's code result by ax works out.

like image 25
hamza Avatar answered Mar 02 '23 09:03

hamza