在matplotlib中使颜色变暗或变亮

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在matplotlib中使颜色变暗或变亮相关的知识,希望对你有一定的参考价值。

假设我在Matplotlib中有颜色。也许它是一个字符串('k')或rgb元组((0.5, 0.1, 0.8))或甚至一些十六进制(#05FA2B)。 Matplotlib中是否有命令/便利功能可以让我变暗(或变亮)那种颜色。

即有没有matplotlib.pyplot.darken(c, 0.1)或类似的东西?我想我所希望的是,在幕后,将采用一种颜色,将其转换为HSL,然后将L值乘以某个给定因子(地板为0,加上1)或明确设置L值到给定值并返回修改后的颜色。

答案

这是my gist的一个函数,用于减轻我认为可以使用matplotlib已知的任何颜色格式的任何颜色。我认为设置金额> 1可能也会变暗。

def lighten_color(color, amount=0.5):
    """
    Lightens the given color by multiplying (1-luminosity) by the given amount.
    Input can be matplotlib color string, hex string, or RGB tuple.

    Examples:
    >> lighten_color('g', 0.3)
    >> lighten_color('#F034A3', 0.6)
    >> lighten_color((.3,.55,.1), 0.5)
    """
    import matplotlib.colors as mc
    import colorsys
    try:
        c = mc.cnames[color]
    except:
        c = color
    c = colorsys.rgb_to_hls(*mc.to_rgb(c))
    return colorsys.hls_to_rgb(c[0], 1 - amount * (1 - c[1]), c[2])

编辑:事实上,它确实变暗和变亮:

import matplotlib.pyplot as plt
import numpy as np

xs = np.linspace(-1, 1, 100)
plt.plot(xs, 0 * xs, color='b', lw=3)
plt.plot(xs, xs**2, color=lighten_color('b', 0.4), lw=3)
plt.plot(xs, -xs**2, color=lighten_color('b', 1.6), lw=3)

image with example of darken and lighten

编辑2:删除函数中不需要的numpy依赖项。

另一答案

几个月前,我不得不解决这个问题。这个想法是让用户选择一种颜色(任何颜色),软件自动生成一个颜色图(这是用于科学目的的包的一部分)。

在任何情况下,这里都是我用来实现它的代码。你不需要对象的大部分内容,但它会给你你所要求的:

import math

class Color():
    def __init__(self, color, fmt='rgb'):
        self.__initialize__(color, fmt)

    def __initialize__(self, color, fmt='rgb'):
        if fmt == 'rgb':
            self.rgb = (int(color[0]), int(color[1]), int(color[2]))
            self.hex = self._rgb2hex(self.rgb)
            self.hsv = self._rgb2hsv(self.rgb)
            self.rgb0 = self.rgb[0] / 255, self.rgb[1] / 255, self.rgb[2] / 255
        elif fmt == 'rgb0':
            self.rgb = (int(color[0] * 255), int(color[1] * 255), int(color[2] * 255))
            self.hex = self._rgb2hex(self.rgb)
            self.hsv = self._rgb2hsv(self.rgb)
            self.rgb0 = (color[0], color[1], color[2])
        elif fmt == 'hex':
            self.hex = color
            self.rgb = self._hex2rgb(self.hex)
            self.hsv = self._rgb2hsv(self.rgb)
            self.rgb0 = self.rgb[0] / 255, self.rgb[1] / 255, self.rgb[2] / 255
        elif fmt == 'hsv':
            self.hsv = color
            self.rgb = self._hsv2rgb(self.hsv)
            self.hex = self._rgb2hex(self.rgb)
            self.rgb0 = self.rgb[0] / 255, self.rgb[1] / 255, self.rgb[2] / 255
        self.__automaticPalette__()

    def __automaticPalette__(self):
        self.rgbColors = []
        self.hexColors = []
        self.hsvColors = []
        self.rgb0Colors = []
        hsv = self.hsv
        for i in range(255):
            new_hsv = hsv[0], hsv[1], (1 / 255) * i
            self.rgbColors.append(self._hsv2rgb(new_hsv))
            self.hexColors.append(self._rgb2hex(self.rgbColors[-1]))
            self.hsvColors.append(new_hsv)
            r, g, b = self.rgbColors[-1]
            self.rgb0Colors.append((r / 255, g / 255, b / 255))

    def _testPalette(self, o=1):
        from matplotlib import pyplot as plt
        from matplotlib.patches import Rectangle
        if o == 1:
            someX, someY = 0.5, 0.1
            plt.figure()
            s = 1
            currentAxis = plt.gca()
            for x in range(254):
                currentAxis.add_patch(Rectangle((x * s, someY), s, 0.1, alpha=1, color=self.rgb0Colors[x]))
            currentAxis.add_patch(Rectangle((5 * s, someY + 0.07), 30, 0.02, alpha=1, color=self.rgb0))

            plt.ylim(0.1, 0.2)
            plt.xlim(0, (x + 1) * s)
            plt.show()
        elif o == 2:
            local = self.rgb0Colors[90:190][0:-1:10]
            someX, someY = 0.5, 0.1
            plt.figure()
            s = 1
            currentAxis = plt.gca()
            for x in range(len(local)):
                currentAxis.add_patch(Rectangle((x * s, someY), s, 0.1, alpha=1, color=local[x]))
            currentAxis.add_patch(Rectangle((5 * s, someY + 0.07), 30, 0.02, alpha=1, color=self.rgb0))

            plt.ylim(0.1, 0.2)
            plt.xlim(0, (x + 1) * s)
            plt.show()

    def _hex2rgb(self, value):
        # http://stackoverflow.com/questions/214359/converting-hex-color-to-rgb-and-vice-versa
        value = value.lstrip('#')
        lv = len(value)
        return tuple(int(value[i:i + int(lv / 3)], 16) for i in range(0, lv, int(lv / 3)))

    def _rgb2hex(self, rgb):
        # http://stackoverflow.com/questions/214359/converting-hex-color-to-rgb-and-vice-versa
        r = rgb[0]
        g = rgb[1]
        b = rgb[2]
        return '#%02X%02X%02X' % (r, g, b)

    def _hsv2rgb(self, hsv):
        # http://code.activestate.com/recipes/576919-python-rgb-and-hsv-conversion/
        h, s, v = hsv
        h = float(h)
        s = float(s)
        v = float(v)
        h60 = h / 60.0
        h60f = math.floor(h60)
        hi = int(h60f) % 6
        f = h60 - h60f
        p = v * (1 - s)
        q = v * (1 - f * s)
        t = v * (1 - (1 - f) * s)
        r, g, b = 0, 0, 0
        if hi == 0:
            r, g, b = v, t, p
        elif hi == 1:
            r, g, b = q, v, p
        elif hi == 2:
            r, g, b = p, v, t
        elif hi == 3:
            r, g, b = p, q, v
        elif hi == 4:
            r, g, b = t, p, v
        elif hi == 5:
            r, g, b = v, p, q
        r, g, b = int(r * 255), int(g * 255), int(b * 255)
        return r, g, b

    def _rgb2hsv(self, rgb):
        # http://code.activestate.com/recipes/576919-python-rgb-and-hsv-conversion/
        r, g, b = rgb
        r, g, b = r / 255.0, g / 255.0, b / 255.0
        mx = max(r, g, b)
        mn = min(r, g, b)
        df = mx - mn
        if mx == mn:
            h = 0
        elif mx == r:
            h = (60 * ((g - b) / df) + 360) % 360
        elif mx == g:
            h = (60 * ((b - r) / df) + 120) % 360
        elif mx == b:
            h = (60 * ((r - g) / df) + 240) % 360
        if mx == 0:
            s = 0
        else:
            s = df / mx
        v = mx
        return h, s, v

    def getColor(self, fmt='rgb'):
        if fmt == 'rgb':
            return self.rgb
        elif fmt == 'hex':
            return self.hex
        elif fmt == 'rgb0':
            return self.rgb0
        elif fmt == 'hsv':
            return self.hsv

所以,如果你这样称呼它:

c = Color((51, 153, 255))
# c = Color((0.5, 0.1, 0.8), fmt='rgb0') # It should work with rgb0
# c = Color('#05d4fa', fmt='hex')        # and hex but I don't remember if it was well tested so be careful (the conversions might be messy).
c._testPalette(1)
print(c.rgbColors)

它将返回给你:

Automatically building a colormap from a single color

, 还有这个:

[(0, 0, 0), (0, 0, 1), (0, 1, 2), (0, 1, 3), (0, 2, 4), (0, 3, 5), (1, 3, 6), (1, 4, 7), (1, 4, 8), (1, 5, 9), (1, 6, 10), (2, 6, 11), (2, 7, 12), (2, 7, 13), (2, 8, 14), (2, 9, 15), (3, 9, 16), (3, 10, 17), (3, 10, 18), (3, 11, 19), (3, 12, 20), (4, 12, 21), (4, 13, 22), (4, 13, 23), (4, 14, 24), (4, 15, 25), (5, 15, 26), (5, 16, 27), (5, 16, 28), (5, 17, 29), (5, 18, 30), (6, 18, 31), (6, 19, 32), (6, 19, 32), (6, 20, 34), (6, 21, 35), (7, 21, 36), (7, 22, 36), (7, 22, 38), (7, 23, 39), (7, 24, 40), (8, 24, 40), (8, 25, 42), (8, 25, 43), (8, 26, 44), (8, 26, 44), (9, 27, 46), (9, 28, 47), (9, 28, 48), (9, 29, 48), (9, 30, 50), (10, 30, 51), (10, 31, 52), (10, 31, 52), (10, 32, 54), (10, 33, 55), (11, 33, 56), (11, 34, 56), (11, 34, 58), (11, 35, 59), (11, 36, 60), (12, 36, 60)

以上是关于在matplotlib中使颜色变暗或变亮的主要内容,如果未能解决你的问题,请参考以下文章

以编程方式使飞镖中的十六进制颜色变亮或变暗

React Native之Touchable四组件

如何防止工作表在 SwiftUI 中使其后面的视图变暗或删除不必要的填充?

视图 x 位置的通知

如何在 jQuery Mobile 中使覆盖面板后面变暗?

scss 使颜色变亮/变暗