centercmap.py
Go to the documentation of this file.
1import numpy as np
2import matplotlib
3import matplotlib.pyplot as plt
4from mpl_toolkits.axes_grid1 import AxesGrid
5
6# See: http://stackoverflow.com/questions/7404116/defining-the-midpoint-of-a-colormap-in-matplotlib
7
8def centercmap(cmap, clim, center=0., shrink=0.):
9 m = (center-clim[0])/(clim[1]-clim[0])
10 start = 0.0 + shrink/2.
11 stop = 1.0 - shrink/2.
12 return shiftedColorMap(cmap, start, m, stop)
13
14
15
16
17
18def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'):
19 '''
20 Function to offset the "center" of a colormap. Useful for
21 data with a negative min and positive max and you want the
22 middle of the colormap's dynamic range to be at zero
23
24 Input
25 -----
26 cmap : The matplotlib colormap to be altered
27 start : Offset from lowest point in the colormap's range.
28 Defaults to 0.0 (no lower ofset). Should be between
29 0.0 and `midpoint`.
30 midpoint : The new center of the colormap. Defaults to
31 0.5 (no shift). Should be between 0.0 and 1.0. In
32 general, this should be 1 - vmax/(vmax + abs(vmin))
33 For example if your data range from -15.0 to +5.0 and
34 you want the center of the colormap at 0.0, `midpoint`
35 should be set to 1 - 5/(5 + 15)) or 0.75
36 stop : Offset from highets point in the colormap's range.
37 Defaults to 1.0 (no upper ofset). Should be between
38 `midpoint` and 1.0.
39 '''
40 cdict = {
41 'red': [],
42 'green': [],
43 'blue': [],
44 'alpha': []
45 }
46
47 # regular index to compute the colors
48 reg_index = np.linspace(start, stop, 257)
49
50 # shifted index to match the data
51 shift_index = np.hstack([
52 np.linspace(0.0, midpoint, 128, endpoint=False),
53 np.linspace(midpoint, 1.0, 129, endpoint=True)
54 ])
55
56 for ri, si in zip(reg_index, shift_index):
57 r, g, b, a = cmap(ri)
58
59 cdict['red'].append((si, r, r))
60 cdict['green'].append((si, g, g))
61 cdict['blue'].append((si, b, b))
62 cdict['alpha'].append((si, a, a))
63
64 newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict)
65 plt.register_cmap(cmap=newcmap)
66
67 return newcmap
subroutine append(buffer, i, d)
def centercmap(cmap, clim, center=0., shrink=0.)
Definition: centercmap.py:8
def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap')
Definition: centercmap.py:18
def abs(send)
Definition: coplot.py:1122