How can I draw a log-normalized imshow plot with a colorbar representing the raw data in matplotlib

Posted by Adam Fraser on Stack Overflow See other posts from Stack Overflow or by Adam Fraser
Published on 2010-03-30T15:29:23Z Indexed on 2010/03/30 15:33 UTC
Read the original article Hit count: 291

Filed under:
|
|

I'm using matplotlib to plot log-normalized images but I would like the original raw image data to be represented in the colorbar rather than the [0-1] interval. I get the feeling there's a more matplotlib'y way of doing this by using some sort of normalization object and not transforming the data beforehand... in any case, there could be negative values in the raw image.

import matplotlib.pyplot as plt
import numpy as np

def log_transform(im):
    '''returns log(image) scaled to the interval [0,1]'''
    try:
        (min, max) = (im[im > 0].min(), im.max())
        if (max > min) and (max > 0):
            return (np.log(im.clip(min, max)) - np.log(min)) / (np.log(max) - np.log(min))
    except:
        pass
    return im

a = np.ones((100,100))
for i in range(100): a[i] = i
f = plt.figure()
ax = f.add_subplot(111)
res = ax.imshow(log_transform(a))
# the colorbar drawn shows [0-1], but I want to see [0-99]
cb = f.colorbar(res)

I've tried using cb.set_array, but that didn't appear to do anything, and cb.set_clim, but that rescales the colors completely.

Thanks in advance for any help :)

© Stack Overflow or respective owner

Related posts about python

Related posts about matplotlib