Darken or lighten a color in matplotlib

前端 未结 3 945
闹比i
闹比i 2021-02-02 08:38

Say I have a color in Matplotlib. Maybe it\'s a string (\'k\') or an rgb tuple ((0.5, 0.1, 0.8)) or even some hex (#05FA2B). Is there a

3条回答
  •  抹茶落季
    2021-02-02 08:59

    Here is a function from my gist to lighten any color that I think will work with any color format known to matplotlib. I think setting an amount > 1 might darken too.

    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])
    

    EDIT: Indeed, it does darken as well as lighten:

    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)
    

    Edit 2: Removed un-needed numpy dependency in the function.

    Edit 3: Function modified with improvements from @FLekschas

    def adjust_lightness(color, amount=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], max(0, min(1, amount * c[1])), c[2])
    

提交回复
热议问题