How to set the color equivalent of matplotlib colorbar?

I would like to display a color panel representing the raw values ​​of the image along the side of the matplotlib imshow subplot, which displays this image, normalized.

I managed to make the image and color bar look similar, but the colorbar min and max values ​​are a normalized (0,1) image instead of an raw image (0,99).

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 is better at mastering the colorbar API, I'd love to hear from you.

Thanks! Adam

+4
source share
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 above snippet is based on the code in your answer; here's a complete, standalone 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 said in the comment above, I would choose a cleaner namespace that you have, for example, there are modules with the same name in NumPy and Matplotlib.

In particular, I would use this import statement to import the Matplotlib "core" graphic functions:

 from matplotlib import pyplot as PLT 

Of course, this does not give the full matplotlib namespace (which really is the point of this import statement), although usually this is all you need.

+7
source

I know that it may be too late, but ... For me, in the last line of Adam's code, result is replaced with ax .

+1
source

Source: https://habr.com/ru/post/1305464/


All Articles