This notebook aims to present several ways to manage color palette with python, mainly for plot purpose.
In [1]:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from IPython.display import HTML # intégration notebook
%matplotlib inline
In [2]:
def plot_cmap(cmap, ncolor=6):
"""
A convenient function to plot colors of a matplotlib cmap
Args:
ncolor (int): number of color to show
cmap: a cmap object or a matplotlib color name
"""
if isinstance(cmap, str):
try:
cm = plt.get_cmap(cmap)
except ValueError:
print("WARNINGS :", cmap, " is not a known colormap")
cm = plt.cm.gray
else:
cm = cmap
with plt.rc_context(plt.rcParamsDefault):
fig = plt.figure(figsize=(6, 1), frameon=False)
ax = fig.add_subplot(111)
ax.pcolor(np.linspace(1, ncolor, ncolor).reshape(1, ncolor), cmap=cm)
ax.set_title(cm.name)
xt = ax.set_xticks([])
yt = ax.set_yticks([])
return fig
In [3]:
def show_colors(colors):
"""
Draw a square for each color contained in the colors list
given in argument.
"""
with plt.rc_context(plt.rcParamsDefault):
fig = plt.figure(figsize=(6, 1), frameon=False)
ax = fig.add_subplot(111)
for x, color in enumerate(colors):
ax.add_patch(
mpl.patches.Rectangle(
(x, 0), 1, 1, facecolor=color
)
)
ax.set_xlim((0, len(colors)))
ax.set_ylim((0, 1))
ax.set_xticks([])
ax.set_yticks([])
ax.set_aspect("equal")
return fig
HTML color codes are another way to define a RGB color using an hexadecimal numeral system.
example : #2D85C9
<-> (48, 133, 201)
alpha
(canal alpha)
In [4]:
plot_cmap("Dark2", 4)
Out[4]:
In [5]:
plot_cmap("Dark2", 4).savefig("img/qualitative.png", bbox_inches="tight")
In [6]:
plot_cmap("Blues", 8)
Out[6]:
In [7]:
plot_cmap("Blues", 8).savefig("img/sequentielle.png", bbox_inches="tight")
In [8]:
plot_cmap("Blues_r", 8)
Out[8]:
In [9]:
plot_cmap("Blues_r", 8).savefig("img/sequentielle_r.png", bbox_inches="tight")
In [10]:
plot_cmap("coolwarm", 9)
Out[10]:
In [11]:
plot_cmap("coolwarm", 9).savefig("img/divergente.png", bbox_inches="tight")
In [12]:
plot_cmap(plt.cm.summer, 6)
Out[12]:
In [13]:
plot_cmap(plt.cm.summer, 6).savefig("img/summer.png", bbox_inches="tight")
colormap
returns a rgba
color.
In [14]:
plt.cm.summer(X=42)
Out[14]:
plt.cm.colormap.N
In [15]:
print("Max val = ", plt.cm.summer.N)
palette = plt.cm.summer(X=[1, 50, 100, 200], alpha=.6)
print(palette)
show_colors(palette)
Out[15]:
In [16]:
show_colors(palette).savefig("img/mpl_palette1.png")
Normalize
In [17]:
normalize = mpl.colors.Normalize(vmin=-5, vmax=5)
palette = plt.cm.summer(X=normalize([-4, -2, 0, 2, 4]), alpha=1)
print(palette)
show_colors(palette)
Out[17]:
In [18]:
show_colors(palette).savefig("img/mpl_palette2.png")
In [19]:
import colorlover as cl
Colorlover provides function to set up a color palette
import colorlover as cl
cl.colorsys
: conversion between color modelscl.scales
: color palettecl.to_HTML
: help function to show the palettecl.scales
has to be used following :
cl.scales["number"]["type"]["name"]
where
number
is a number between 3 and 12 includedtype
is : div
, seq
or qual
name
is the palette nameAll palettes are not available for all combinations.
For example, this is divergent palettes with 4 colors. You have to use cl.to_html
to get an html version and HTML()
to ask the notebook to display the html code and show the palette.
In [20]:
HTML(cl.to_html(cl.scales["4"]["div"]))
Out[20]:
Divergent color palette PuOr
with 4 colors :
In [21]:
cl.scales["4"]["div"]["PuOr"]
Out[21]:
In [22]:
cl.to_numeric(cl.scales["4"]["div"]["PuOr"])
Out[22]:
In [24]:
import seaborn as sns
The documentation is really clear and provides a nice tutorial seaborn color palettes. The following juste provides simple exampl cases.
import seaborn as sns
seaborn provides several functions in order to build and show color palettes. For example, in order to show the current palette :
In [29]:
current_palette = sns.color_palette()
sns.palplot(current_palette)
In [26]:
sns.palplot(sns.color_palette("husl", 8))
In [27]:
sns.palplot(sns.light_palette("violet", 4))
In [28]:
sns.palplot(sns.diverging_palette(220, 20, n=5))