Last active
September 28, 2020 14:57
-
-
Save ebressert/32806ac1c95461349522 to your computer and use it in GitHub Desktop.
Advanced color editing for Matplotlib and Seaborn
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import colorsys | |
import numpy as np | |
import matplotlib.pyplot as plt | |
import seaborn as sns | |
%matplotlib inline | |
def alter(alist, col, factor=1.1): | |
tmp = np.array(alist) | |
tmp[:,col] = tmp[:,col] * factor | |
tmp[tmp > 1] = 1 | |
tmp[tmp < 0] = 0 | |
new = [] | |
for row in tmp.tolist(): | |
new.append(tuple(row)) | |
return new | |
def rgb2hls(alist): | |
alist = alist[:] | |
for i, row in enumerate(alist): | |
hls = colorsys.rgb_to_hls(row[0], row[1], row[2]) | |
alist[i] = hls | |
return alist | |
def hls2rgb(alist): | |
alist = alist[:] | |
for i, row in enumerate(alist): | |
hls = colorsys.hls_to_rgb(row[0], row[1], row[2]) | |
alist[i] = hls | |
return alist | |
def lighten(alist, increase=0.2): | |
factor = 1 + increase | |
hls = rgb2hls(alist) | |
new = alter(hls, 1, factor=factor) | |
rgb = hls2rgb(new) | |
return rgb | |
def darken(alist, decrease=0.2): | |
factor = 1 - decrease | |
hls = rgb2hls(alist) | |
new = alter(hls, 1, factor=factor) | |
rgb = hls2rgb(new) | |
return rgb | |
def saturate(alist, increase=0.2): | |
factor = 1 + increase | |
hls = rgb2hls(alist) | |
new = alter(hls, 2, factor=factor) | |
rgb = hls2rgb(new) | |
return rgb | |
def desaturate(alist, decrease=0.2): | |
factor = 1 - decrease | |
hls = rgb2hls(alist) | |
new = alter(hls, 2, factor=factor) | |
rgb = hls2rgb(new) | |
return rgb | |
#Visual examples | |
copal = sns.color_palette("hls", 7) | |
sns.palplot(copal) | |
sns.palplot(lighten(copal)) | |
sns.palplot(darken(copal)) | |
sns.palplot(saturate(copal)) | |
sns.palplot(desaturate(copal)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Creating custom colormaps has been made much easier with Seaborn, but it still lacks the ability to customize the colormaps at finer granularity, e.g., saturation and light levels. This is some code that I wrote up to allow quick editing of the color maps to get just what you want.