3 import matplotlib
.pyplot
as plt
5 def shiftedColorMap(cmap
, start
=0, midpoint
=0.5, stop
=1.0, name
='shiftedcmap'):
7 Function to offset the "center" of a colormap. Useful for
8 data with a negative min and positive max and you want the
9 middle of the colormap's dynamic range to be at zero.
13 cmap : The matplotlib colormap to be altered
14 start : Offset from lowest point in the colormap's range.
15 Defaults to 0.0 (no lower offset). Should be between
17 midpoint : The new center of the colormap. Defaults to
18 0.5 (no shift). Should be between 0.0 and 1.0. In
19 general, this should be 1 - vmax / (vmax + abs(vmin))
20 For example if your data range from -15.0 to +5.0 and
21 you want the center of the colormap at 0.0, `midpoint`
22 should be set to 1 - 5/(5 + 15)) or 0.75
23 stop : Offset from highest point in the colormap's range.
24 Defaults to 1.0 (no upper offset). Should be between
34 # regular index to compute the colors
35 reg_index
= np
.linspace(start
, stop
, 257)
37 # shifted index to match the data
38 shift_index
= np
.hstack([
39 np
.linspace(0.0, midpoint
, 128, endpoint
=False),
40 np
.linspace(midpoint
, 1.0, 129, endpoint
=True)
43 for ri
, si
in zip(reg_index
, shift_index
):
46 cdict
['red'].append((si
, r
, r
))
47 cdict
['green'].append((si
, g
, g
))
48 cdict
['blue'].append((si
, b
, b
))
49 cdict
['alpha'].append((si
, a
, a
))
51 newcmap
= matplotlib
.colors
.LinearSegmentedColormap(name
, cdict
)
52 plt
.register_cmap(cmap
=newcmap
)