1

I'm currently working to plot some labels over the x,y axis in imshow, but over 95% of the points sit in the 0-0.2 range, whereas less than 10% sit in the 0.2-1.0 range. Using the default 'jet' colourmap, this results in almost all the plots showing up as blue, even though there is variance in 95% of the data that becomes visually unobservable.

Is there a way to tell matplotlib to, for example, quadruple the rate at which the colours change in the 0.0-0.1 range, and scale the remaining 0.2-1.0 range accordingly? Any help would be greatly appreciated.

Thanks in advance!

EDIT: Seeing at this is just a visual representation, I realised that one option I have is to instead re-scale the data in the 0.2 range down to whatever value I see fit so that the changes are more visible, then manually create the colour bar accordingly. I would still prefer to be able to have matplotlib's imshow do this natively if at all possible though.

mediantis
  • 145
  • 3
  • 14
  • 2
    A general tip: don't ever use the `jet` colormap. In 99.9% of cases, there is a better choice. The new standard colormap in matplotlib 2 is `viridis`. It is more pleasing to the eye, color-blind friendly and displays data in a more logical way without false implications like `jet` does. Edit: [This video](https://www.youtube.com/watch?v=xAoljeRJ3lU) says everything about why `jet` is bad. – Ian Oct 28 '16 at 09:57
  • Thanks for the tip - I've come across that statement here and there, without paying it too much attention. I'll give it a shot! – mediantis Oct 28 '16 at 11:12
  • Did you read the [Colormap Normalization arcticle](http://matplotlib.org/users/colormapnorms.html) on the matplotlib site? – ImportanceOfBeingErnest Oct 28 '16 at 15:10
  • @ImportanceOfBeingErnest I have, but can't figure out from there how I would rescale the data *while* still showing the original values correctly on the colour bar. – mediantis Oct 31 '16 at 07:29
  • 1
    I'm not sure if I understand your problem, but the idea of colormap normalization would be not to change your data, but the colormap instead, e.g. to a logarithmic scale. – ImportanceOfBeingErnest Oct 31 '16 at 09:55

1 Answers1

3

In case you want to emphazise small values in your data in an image plot, I would never change the actual data itself. That can lead to a lot of confusion. Instead, as I said in the comments, change the colormap.

Ways of doing so are documented in the Matplotlib Color Normalization Tutorial as well as here on SO. Especially this article and the answers within are really illustrative of the possibilities one has.

I combined two concepts in the example below to show the options.

  • One is to rescale the colormap such that the value that initially was at the middle (midpoint) of your colormap is shifted down. In this way more variation is added between 0 and the new midpoint, while everything above is stretched. One can think of this as two linear colormaps spliced together.
  • The other is to simply use a logarithmic scaling of the colors.

This is the example code

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.colors as colors


def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'):
    '''
    function taken from
    https://stackoverflow.com/questions/7404116/...
        ...defining-the-midpoint-of-a-colormap-in-matplotlib
    Function to offset the "center" of a colormap. Useful for
    data with a negative min and positive max and you want the
    middle of the colormap's dynamic range to be at zero

    Input
    -----
      cmap : The matplotlib colormap to be altered
      start : Offset from lowest point in the colormap's range.
          Defaults to 0.0 (no lower ofset). Should be between
          0.0 and `midpoint`.
      midpoint : The new center of the colormap. Defaults to 
          0.5 (no shift). Should be between 0.0 and 1.0. In
          general, this should be  1 - vmax/(vmax + abs(vmin))
          For example if your data range from -15.0 to +5.0 and
          you want the center of the colormap at 0.0, `midpoint`
          should be set to  1 - 5/(5 + 15)) or 0.75
      stop : Offset from highets point in the colormap's range.
          Defaults to 1.0 (no upper ofset). Should be between
          `midpoint` and 1.0.
    '''
    cdict = {  'red': [],  'green': [], 'blue': [],  'alpha': []  }

    # regular index to compute the colors
    reg_index = np.linspace(start, stop, 257)

    # shifted index to match the data
    shift_index = np.hstack([
        np.linspace(0.0, midpoint, 128, endpoint=False), 
        np.linspace(midpoint, 1.0, 129, endpoint=True)
    ])

    for ri, si in zip(reg_index, shift_index):
        r, g, b, a = cmap(ri)

        cdict['red'].append((si, r, r))
        cdict['green'].append((si, g, g))
        cdict['blue'].append((si, b, b))
        cdict['alpha'].append((si, a, a))

    newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict)
    plt.register_cmap(cmap=newcmap)

    return newcmap


x = np.linspace(-3, 3, num=601)
X,Y = np.meshgrid(x,x)
Z = np.sinc( (X*np.cos(1)+Y*np.sin(1))**2 +(-X*np.sin(1)+0.2*Y*np.cos(1))**2 )**2 

orig_cmap = matplotlib.cm.viridis 
shifted_cmap = shiftedColorMap(orig_cmap, midpoint=0.05, name='shifted')


fig = plt.figure(figsize=(4,9))
ax = [fig.add_subplot(3,1,n+1) for n in range(3)]

# normal cmap
im0 = ax[0].imshow(Z, interpolation="none", cmap=orig_cmap)
fig.colorbar(im0, ax=ax[0])
ax[0].set_title('Default behavior (hard to see small values)', fontsize=10)

#example using the custom shiftedColorMap function
#taken from https://stackoverflow.com/questions/7404116/defining-the-midpoint-of-a-colormap-in-matplotlib
im1 = ax[1].imshow(Z, interpolation="none", cmap=shifted_cmap)
fig.colorbar(im1, ax=ax[1])
ax[1].set_title('Center of colormap shifted to 0.05', fontsize=10)

#example using colors.LogNorm()
#taken from http://matplotlib.org/users/colormapnorms.html
im2 = ax[2].imshow(Z, interpolation="none", norm=colors.LogNorm(vmin=10e-5, vmax=Z.max()), cmap=orig_cmap)
fig.colorbar(im2, ax=ax[2])
ax[2].set_title('Logarithmically scaled Colormap', fontsize=10)

for axis in ax:
    axis.set_yticks([])
    axis.set_xticks([])
plt.tight_layout()    
plt.show() 

producing

enter image description here

Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712