Skip to content

Instantly share code, notes, and snippets.

@Splines
Forked from ihincks/lighten_color.py
Last active February 24, 2022 00:43
Show Gist options
  • Save Splines/93aaaa713b6cc53ae3693d07f47e194b to your computer and use it in GitHub Desktop.
Save Splines/93aaaa713b6cc53ae3693d07f47e194b to your computer and use it in GitHub Desktop.
Function to lighten any color in matplotlib
def change_brightness(color, amount=1):
"""
Changes the brightness of the given color by multiplying luminosity
by the given amount.
Input can be a matplotlib color string, hex string, or RGB tuple.
The color gets brighter when amount > 1 and darker when amount < 1.
The resulting luminosity is restricted to [0,1].
Examples:
>> lighten_color('g', 0.3)
>> lighten_color('#F034A3', 0.6)
>> lighten_color((.3,.55,.1), 0.5)
"""
# adapted from
# https://gist.github.com/ihincks/6a420b599f43fcd7dbd79d56798c4e5a
# https://stackoverflow.com/a/49601444/9655481
import colorsys
import matplotlib.colors as mc
import numpy as np
try:
c = mc.cnames[color]
except:
c = color
c = np.array(colorsys.rgb_to_hls(*mc.to_rgb(c)))
hls = (c[0], max(0, min(1, amount * c[1])), c[2])
rgb = colorsys.hls_to_rgb(*hls)
return mc.to_hex(rgb)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment