Skip to content

Instantly share code, notes, and snippets.

@kingjr
Last active August 29, 2015 14:09
Show Gist options
  • Save kingjr/99842fc9b0c3c6ca2f6b to your computer and use it in GitHub Desktop.
Save kingjr/99842fc9b0c3c6ca2f6b to your computer and use it in GitHub Desktop.
import numpy as np
from matplotlib.colors import LinearSegmentedColormap
class nlcmap(LinearSegmentedColormap):
"""
nlcmap - a nonlinear cmap from specified levels
Copyright (c) 2006-2007, Robert Hetland <[email protected]>
Release under MIT license.
Some hacks added 2012 noted in code (@MRR)
"""
def __init__(self, cmap, levels):
if isinstance(cmap, str):
cmap = plt.get_cmap(cmap)
self.cmap = cmap
self.N = cmap.N
self.monochrome = self.cmap.monochrome
self.levels = np.asarray(levels, dtype='float64')
self._x = self.levels / self.levels.max()
self._y = np.linspace(0.0, 1.0, len(self.levels))
def __call__(self, xi, alpha=1.0, **kw):
yi = np.interp(xi, self._x, self._y)
return self.cmap(yi, alpha)
def logcenter(center, x=None):
# Authors: Jean-Remi King, <[email protected]>
# Clément Levrard <[email protected]>
#
# License: BSD (3-clause)
"""
Creates a logarithmic scale centered around center, and bounded between
[0., 1.] such that:
f(0, center) = 0
f(1, center) = 1
f(center, center) = .5
Parameters
----------
x : float | np.array | None
If float or np.array, 0. < x < 1.
If None, set to np.linspace(0., 1., 256).
Defaults to None.
center : float
0. < center < 1.
Returns
-------
y : float | np.array
"""
from numpy import exp, log
if x is None:
x = np.linspace(0., 1., 256)
if center >= 1. or center <= 0.:
raise ValueError('center must be between 0 and 1')
if center == .5:
y = x
else:
n = 1. / center
y = (exp(2 * log(n - 1) * x) - 1) / (n * (n - 2))
if center > .5:
y = 1. - y
return y
# Example
import matplotlib.pyplot as plt
from pylab import mgrid
yy, xx = mgrid[0.0:1.0:100j, 0.0:1.0:100j]
H = (xx + yy) / 2.
# Define color levels with 4 categories
n_classes_list = range(2, 10, 2)
fig, axes = plt.subplots(1, len(n_classes_list))
for n_classes, ax in zip(n_classes_list, axes):
levels = logcenter(1. / n_classes)
cs = ax.contourf(xx, yy, H, levels, cmap=nlcmap('RdBu_r', levels),
aspect='equal')
c = plt.colorbar(cs,ax=ax)
c.set_ticks([0., 1. / n_classes, 1.])
c.set_clim([0., 1.])
ax.set_xticks([])
ax.set_yticks([])
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment