8000 Issue #4271: reversed method added to Colormap objects. by kjartankg · Pull Request #5899 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

Issue #4271: reversed method added to Colormap objects. #5899

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 90 additions & 1 deletion lib/matplotlib/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ def to_rgb(self, arg):
if fl < 0 or fl > 1:
raise ValueError(
'gray (string) must be in range 0-1')
color = (fl,)*3
color = (fl,) * 3
elif cbook.iterable(arg):
if len(arg) > 4 or len(arg) < 3:
raise ValueError(
Expand Down Expand Up @@ -496,6 +496,7 @@ class Colormap(object):
``data->normalize->map-to-color`` processing chain.

"""

def __init__(self, name, N=256):
r"""
Parameters
Expand Down Expand Up @@ -665,6 +666,30 @@ def _resample(self, lutsize):
"""
raise NotImplementedError()

def reversed(self, name=None):
"""
Make a reversed instance of the Colormap.

NOTE: Function not implemented for base class.

Parameters
----------
name : str, optional
The name for the reversed colormap. If it's None the
name will be the name of the parent colormap + "_r".

Raises
------
NotImplementedError
Function not implemented for base class.

Notes
-----
See :meth:`LinearSegmentedColormap.reversed` and
:meth:`ListedColormap.reversed`
"""
raise NotImplementedError()


class LinearSegmentedColormap(Colormap):
"""Colormap objects based on lookup tables using linear segments.
Expand All @@ -673,6 +698,7 @@ class LinearSegmentedColormap(Colormap):
primary color, with the 0-1 domain divided into any number of
segments.
"""

def __init__(self, name, segmentdata, N=256, gamma=1.0):
"""Create color map from linear mapping segments

Expand Down Expand Up @@ -784,6 +810,40 @@ def _resample(self, lutsize):
"""
return LinearSegmentedColormap(self.name, self._segmentdata, lutsize)

def reversed(self, name=None):
"""
Make a reversed instance of the Colormap.

Parameters
----------
name : str, optional
The name for the reversed colormap. If it's None the
name will be the name of the parent colormap + "_r".

Returns
-------
LinearSegmentedColormap
The reversed colormap.
"""
if name is None:
name = self.name + "_r"

# Function factory needed to deal with 'late binding' issue.
def factory(dat):
def func_r(x):
return dat(1.0 - x)
return func_r

data_r = dict()
for key, data in six.iteritems(self._segmentdata):
if six.callable(data):
data_r[key] = factory(data)
else:
new_data = [(1.0 - x, y1, y0) for x, y0, y1 in reversed(data)]
data_r[key] = new_data

return LinearSegmentedColormap(name, data_r, self.N, self._gamma)


class ListedColormap(Colormap):
"""Colormap object generated from a list of colors.
Expand All @@ -792,6 +852,7 @@ class ListedColormap(Colormap):
but it can also be used to generate special colormaps for ordinary
mapping.
"""

def __init__(self, colors, name='from_list', N=None):
"""
Make a colormap from a list of colors.
Expand Down Expand Up @@ -854,13 +915,35 @@ def _resample(self, lutsize):
"""
return ListedColormap(self.name, self.colors, lutsize)

def reversed(self, name=None):
"""
Make a reversed instance of the Colormap.

Parameters
----------
name : str, optional
The name for the reversed colormap. If it's None the
name will be the name of the parent colormap + "_r".

Returns
-------
ListedColormap
A reversed instance of the colormap.
"""
if name is None:
name = self.name + "_r"

colors_r = list(reversed(self.colors))
return ListedColormap(colors_r, name=name, N=self.N)


class Normalize(object):
"""
A class which, when called, can normalize data into
the ``[0.0, 1.0]`` interval.

"""

def __init__(self, vmin=None, vmax=None, clip=False):
"""
If *vmin* or *vmax* is not given, they are initialized from the
Expand Down Expand Up @@ -988,6 +1071,7 @@ class LogNorm(Normalize):
"""
Normalize a given value to the 0-1 range on a log scale
"""

def __call__(self, value, clip=None):
if clip is None:
clip = self.clip
Expand Down Expand Up @@ -1065,6 +1149,7 @@ class SymLogNorm(Normalize):
*linthresh* allows the user to specify the size of this range
(-*linthresh*, *linthresh*).
"""

def __init__(self, linthresh, linscale=1.0,
vmin=None, vmax=None, clip=False):
"""
Expand Down Expand Up @@ -1174,6 +1259,7 @@ class PowerNorm(Normalize):
Normalize a given value to the ``[0, 1]`` interval with a power-law
scaling. This will clip any negative data points to 0.
"""

def __init__(self, gamma, vmin=None, vmax=None, clip=False):
Normalize.__init__(self, vmin, vmax, clip)
self.gamma = gamma
Expand Down Expand Up @@ -1258,6 +1344,7 @@ class BoundaryNorm(Normalize):
simpler, and reduces the number of conversions back and forth
between integer and floating point.
"""

def __init__(self, boundaries, ncolors, clip=False):
"""
*boundaries*
Expand Down Expand Up @@ -1326,6 +1413,7 @@ class NoNorm(Normalize):
want to use indices directly in a
:class:`~matplotlib.cm.ScalarMappable` .
"""

def __call__(self, value, clip=None):
return value

Expand Down Expand Up @@ -1494,6 +1582,7 @@ class LightSource(object):
The :meth:`shade_rgb`
The :meth:`hillshade` produces an illumination map of a surface.
"""

def __init__(self, azdeg=315, altdeg=45, hsv_min_val=0, hsv_max_val=1,
hsv_min_sat=1, hsv_max_sat=0):
"""
Expand Down
12 changes: 12 additions & 0 deletions lib/matplotlib/tests/test_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,18 @@ def _azimuth2math(azimuth, elevation):
return theta, phi


def test_colormap_reversing():
"""Check the generated _lut data of a colormap and corresponding
reversed colormap if they are almost the same."""
for name in six.iterkeys(cm.cmap_d):
cmap = plt.get_cmap(name)
cmap_r = cmap.reversed()
if not cmap_r._isinit:
cmap._init()
cmap_r._init()
assert_array_almost_equal(cmap._lut[:256], cmap_r._lut[255::-1])


if __name__ == '__main__':
import nose
nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
0