Darken or lighten a color in matplotlib

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)

image with example of darken and lighten

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)