From 930ab6395b002bce137f0a84ee80f8692319d215 Mon Sep 17 00:00:00 2001 From: Jake VanderPlas Date: Sun, 28 Sep 2014 18:33:57 -0700 Subject: [PATCH] ENH: add to_grayscale() method to color maps --- lib/matplotlib/colors.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py index 5d165b8f69a0..956f3e76a1bf 100644 --- a/lib/matplotlib/colors.py +++ b/lib/matplotlib/colors.py @@ -665,6 +665,18 @@ def is_gray(self): return (np.alltrue(self._lut[:, 0] == self._lut[:, 1]) and np.alltrue(self._lut[:, 0] == self._lut[:, 2])) + def to_grayscale(self): + """Return a grayscale version of the colormap""" + colors = self(np.arange(self.N)) + + # convert RGBA to perceived greyscale luminance + # cf. http://alienryderflex.com/hsp.html + RGB_weight = [0.299, 0.587, 0.114] + luminance = np.sqrt(np.dot(colors[:, :3] ** 2, RGB_weight)) + colors[:, :3] = luminance[:, np.newaxis] + + return self.from_list(self.name + "_gray", colors, self.N) + class LinearSegmentedColormap(Colormap): """Colormap objects based on lookup tables using linear segments.