- Specifying colors#
- Transparency#
- «CN» color selection#
- Comparison between X11/CSS4 and xkcd colors#
- How to Get a List of N Different Colors and Names in Python/Pandas
- Step 1: Generate N Random Colors with Python
- Step 2: Display N random colors with Python and JupyterLab
- Step 3: Get color palette with seaborn and Python
- Step 4: Get color palette with matplotlib
- Step 5: Working with color names and color values format (HTML and CSS) in Python
Specifying colors#
Matplotlib recognizes the following formats to specify a color.
RGB or RGBA (red, green, blue, alpha) tuple of float values in a closed interval [0, 1].
Case-insensitive hex RGB or RGBA string.
Case-insensitive RGB or RGBA string equivalent hex shorthand of duplicated characters.
String representation of float value in closed interval [0, 1] for grayscale values.
Single character shorthand notation for some basic colors.
The colors green, cyan, magenta, and yellow do not coincide with X11/CSS4 colors. Their particular shades were chosen for better visibility of colored lines against typical backgrounds.
- ‘b’ as blue
- ‘g’ as green
- ‘r’ as red
- ‘c’ as cyan
- ‘m’ as magenta
- ‘y’ as yellow
- ‘k’ as black
- ‘w’ as white
Case-insensitive X11/CSS4 color name with no spaces.
Case-insensitive color name from xkcd color survey with ‘xkcd:’ prefix.
Case-insensitive Tableau Colors from ‘T10’ categorical palette.
This is the default color cycle.
- ‘tab:blue’
- ‘tab:orange’
- ‘tab:green’
- ‘tab:red’
- ‘tab:purple’
- ‘tab:brown’
- ‘tab:pink’
- ‘tab:gray’
- ‘tab:olive’
- ‘tab:cyan’
«CN» color spec where ‘C’ precedes a number acting as an index into the default property cycle.
Matplotlib indexes color at draw time and defaults to black if cycle does not include color.
rcParams[«axes.prop_cycle»] (default: cycler(‘color’, [‘#1f77b4’, ‘#ff7f0e’, ‘#2ca02c’, ‘#d62728’, ‘#9467bd’, ‘#8c564b’, ‘#e377c2’, ‘#7f7f7f’, ‘#bcbd22’, ‘#17becf’]) )
«Red», «Green», and «Blue» are the intensities of those colors. In combination, they represent the colorspace.
Transparency#
The alpha value of a color specifies its transparency, where 0 is fully transparent and 1 is fully opaque. When a color is semi-transparent, the background color will show through.
The alpha value determines the resulting color by blending the foreground color with the background color according to the formula
The following plot illustrates the effect of transparency.
import matplotlib.pyplot as plt from matplotlib.patches import Rectangle import numpy as np fig, ax = plt.subplots(figsize=(6.5, 1.65), layout='constrained') ax.add_patch(Rectangle((-0.2, -0.35), 11.2, 0.7, color='C1', alpha=0.8)) for i, alpha in enumerate(np.linspace(0, 1, 11)): ax.add_patch(Rectangle((i, 0.05), 0.8, 0.6, alpha=alpha, zorder=0)) ax.text(i+0.4, 0.85, f"alpha:.1f>", ha='center') ax.add_patch(Rectangle((i, -0.05), 0.8, -0.6, alpha=alpha, zorder=2)) ax.set_xlim(-0.2, 13) ax.set_ylim(-1, 1) ax.set_title('alpha values') ax.text(11.3, 0.6, 'zorder=1', va='center', color='C0') ax.text(11.3, 0, 'zorder=2\nalpha=0.8', va='center', color='C1') ax.text(11.3, -0.6, 'zorder=3', va='center', color='C0') ax.axis('off')
The orange rectangle is semi-transparent with alpha = 0.8. The top row of blue squares is drawn below and the bottom row of blue squares is drawn on top of the orange rectangle.
See also Zorder Demo to learn more on the drawing order.
«CN» color selection#
Matplotlib converts «CN» colors to RGBA when drawing Artists. The Styling with cycler section contains additional information about controlling colors and style properties.
import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl th = np.linspace(0, 2*np.pi, 128) def demo(sty): mpl.style.use(sty) fig, ax = plt.subplots(figsize=(3, 3)) ax.set_title('style: '.format(sty), color='C0') ax.plot(th, np.cos(th), 'C1', label='C1') ax.plot(th, np.sin(th), 'C2', label='C2') ax.legend() demo('default') demo('seaborn-v0_8')
The first color ‘C0’ is the title. Each plot uses the second and third colors of each style’s rcParams[«axes.prop_cycle»] (default: cycler(‘color’, [‘#1f77b4’, ‘#ff7f0e’, ‘#2ca02c’, ‘#d62728’, ‘#9467bd’, ‘#8c564b’, ‘#e377c2’, ‘#7f7f7f’, ‘#bcbd22’, ‘#17becf’]) ). They are ‘C1’ and ‘C2’ , respectively.
Comparison between X11/CSS4 and xkcd colors#
95 out of the 148 X11/CSS4 color names also appear in the xkcd color survey. Almost all of them map to different color values in the X11/CSS4 and in the xkcd palette. Only ‘black’, ‘white’ and ‘cyan’ are identical.
For example, ‘blue’ maps to ‘#0000FF’ whereas ‘xkcd:blue’ maps to ‘#0343DF’ . Due to these name collisions, all xkcd colors have the ‘xkcd:’ prefix.
The visual below shows name collisions. Color names where color values agree are in bold.
import matplotlib.colors as mcolors import matplotlib.patches as mpatch overlap = name for name in mcolors.CSS4_COLORS if f'xkcd:name>' in mcolors.XKCD_COLORS> fig = plt.figure(figsize=[9, 5]) ax = fig.add_axes([0, 0, 1, 1]) n_groups = 3 n_rows = len(overlap) // n_groups + 1 for j, color_name in enumerate(sorted(overlap)): css4 = mcolors.CSS4_COLORS[color_name] xkcd = mcolors.XKCD_COLORS[f'xkcd:color_name>'].upper() # Pick text colour based on perceived luminance. rgba = mcolors.to_rgba_array([css4, xkcd]) luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2] css4_text_color = 'k' if luma[0] > 0.5 else 'w' xkcd_text_color = 'k' if luma[1] > 0.5 else 'w' col_shift = (j // n_rows) * 3 y_pos = j % n_rows text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None) ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4)) ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd)) ax.text(0.5 + col_shift, y_pos + .7, css4, color=css4_text_color, ha='center', **text_args) ax.text(1.5 + col_shift, y_pos + .7, xkcd, color=xkcd_text_color, ha='center', **text_args) ax.text(2 + col_shift, y_pos + .7, f' color_name>', **text_args) for g in range(n_groups): ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1) ax.text(0.5 + 3*g, -0.3, 'X11/CSS4', ha='center') ax.text(1.5 + 3*g, -0.3, 'xkcd', ha='center') ax.set_xlim(0, 3 * n_groups) ax.set_ylim(n_rows, -1) ax.axis('off') plt.show()
Total running time of the script: ( 0 minutes 2.179 seconds)
How to Get a List of N Different Colors and Names in Python/Pandas
Looking to generate a list of different colors or get color names in Python? We are going to demonstrate combination of different modules like:
In order to generate, list color names and values. Also we can see how to work with color palettes and HTML/CSS values.
If so, you’ll see the options to accomplish these goals using simple examples.
Step 1: Generate N Random Colors with Python
In this step we will get a list of many different colors as hex values in Python. We are going to use pure Python code and will generate a list of unique colors with randomint and for loop:
from random import randint color = [] n = 10 for i in range(n): color.append('#%06X' % randint(0, 0xFFFFFF))
This will generate a list like:
[‘#4E8CA1’, ‘#F9C1E7’, ‘#933D05’, ‘#595697’, ‘#417D22’, ‘#7D8377’, ‘#624F7B’, ‘#C25D39’, ‘#A24AFD’, ‘#2AED9E’]
You need to provide just the number of the random colors to be generated.
Step 2: Display N random colors with Python and JupyterLab
To display the different colors generated from the above code we are going to use Pandas.
First we are going to define a function which is going to display each row of a Pandas DataFrame in a different color(more example on formatting — How to Set Pandas DataFrame Background Color Based On Condition) :
from random import randint def format_color_groups(df, color): x = df.copy() i = 0 for factor in color: style = f'background-color: ' x.loc[i] = style i = i + 1 return x
Next we are going to generate a DataFrame with a random integers (more info — How to Create a Pandas DataFrame of Random Integers:
from random import randint import numpy as np import pandas as pd color = [] n = 10 df = pd.DataFrame(np.random.randint(0,n,size=(n, 2)), columns=list('AB'))
Finally we are going to apply the function to the generated DataFrame and pass the list of colors:
df.style.apply(format_color_groups, color=color, axis=None)
A | B | |
---|---|---|
0 | 4 | 4 |
1 | 3 | 4 |
2 | 5 | 0 |
3 | 5 | 1 |
4 | 8 | 2 |
5 | 7 | 4 |
6 | 3 | 2 |
7 | 5 | 0 |
8 | 2 | 1 |
9 | 8 | 9 |
Step 3: Get color palette with seaborn and Python
Python package seaborn offers color palettes with different styles. You can find more about it: seaborn.color_palette
Below you can find a simple example:
import seaborn as sns sns.color_palette()
sns.color_palette("flare") sns.color_palette("pastel")
You can find the generated colors on the image below:
How many colors to generate depends on a parameter:
palette = sns.color_palette(None, 3)
Step 4: Get color palette with matplotlib
Another option to get different color palettes in Python is with the package matplotlib. After installing it you can generate different color ranges with code like:
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib import cm from collections import OrderedDict cmaps = OrderedDict() cmaps['Miscellaneous'] = [ 'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg', 'gist_rainbow', 'rainbow', 'jet', 'turbo', 'nipy_spectral', 'gist_ncar'] gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) def plot_color_gradients(cmap_category, cmap_list): # Create figure and adjust figure height to number of colormaps nrows = len(cmap_list) figh = 0.35 + 0.15 + (nrows + (nrows - 1) * 0.1) * 0.22 fig, axs = plt.subplots(nrows=nrows + 1, figsize=(6.4, figh)) fig.subplots_adjust(top=1 - 0.35 / figh, bottom=0.15 / figh, left=0.2, right=0.99) axs[0].set_title(cmap_category + ' colormaps', fontsize=14) for ax, name in zip(axs, cmap_list): ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name)) ax.text(-0.01, 0.5, name, va='center', ha='right', fontsize=10, transform=ax.transAxes) # Turn off *all* ticks & spines, not just the ones with colormaps. for ax in axs: ax.set_axis_off() for cmap_category, cmap_list in cmaps.items(): plot_color_gradients(cmap_category, cmap_list) plt.show()
Step 5: Working with color names and color values format (HTML and CSS) in Python
Additional library webcolors is available if you need to:
- get the color name in Python
- convert color name to HTML/CSS or hex format
More about this Python module: webcolors.
And example usage of converting hex value to color name:
import webcolors webcolors.hex_to_name(u'#daa520') webcolors.hex_to_name(u'#000000') webcolors.hex_to_name(u'#FFFFFF')
On the other hand if you like to get the color value based on its name you can do:
webcolors.html5_parse_legacy_color(u'lime') webcolors.html5_parse_legacy_color(u'salmon')
By using DataScientYst — Data Science Simplified, you agree to our Cookie Policy.