Explain Codes LogoExplain Codes Logo

Named colors in matplotlib

python
matplotlib
color-palette
plotting
Alex KataevbyAlex Kataev·Sep 8, 2024
⚡TLDR

Quickly plot with matplotlib using color names for the color parameter, eliminating the need to remember RGB codes.

import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6], color='orchid') # Who knew flowers could code? plt.show()

For a complete list of available colors, refer to the matplotlib.colors.CSS4_COLORS dictionary which pairs color names and HEX codes.

Expanding your color toolbox in matplotlib

XKCD and Tableau color palettes

Beyond CSS colors, matplotlib opens doors to a wider color spectrum via the xkcd palette, accessible with the xkcd: prefix:

plt.plot([1, 2, 3], [4, 5, 6], color='xkcd:sky blue') # Feels like we're in the cloud... computing.

Similarly, Tableau's vibrant palette is also available using the 'tab:' prefix, giving your plots that jazz they need:

plt.plot([1, 2, 3], [4, 5, 6], color='tab:orange') # Honestly, fruit names should be a universal color standard.

Precision coloring with HTML hex codes

Use HTML hex codes while plotting if you're eyeing that exact shade or replicating design/brand colors:

plt.plot([1, 2, 3], [4, 5, 6], color='#FFA07A') # Also tastes great with sushi. (Only joking.)

Contributing to the rainbow: list and visualize all named colors

Generate a visual grid of all available colors with this code snippet. Great for choosing the perfect color for your plot:

import matplotlib.pyplot as plt import matplotlib.colors as mcolors fig, ax = plt.subplots(figsize=(8, 5)) colormap = list(mcolors.CSS4_COLORS) for i, color in enumerate(colormap): ax.add_patch(plt.Rectangle((i, 0), 1, 1, color=color)) ax.set_xlim(0, len(colormap)) ax.set_ylim(0, 1) ax.set_xticks([]) ax.set_yticks([]) plt.show()

Replace mcolors.CSS4_COLORS with matplotlib.colors.XKCD_COLORS or matplotlib.colors.TABLEAU_COLORS to explore xkcd and Tableau palettes.

The buried treasure of matplotlib: _color_data.py

Get a step ahead with matplotlib's undisclosed color names found in _color_data.py on GitHub.

Context-aware color choice for data plots

Context matters while coloring your plots. A scatter plot requires colors that stand out from the rest:

plt.scatter(x, y, color='xkcd:bright purple') # Commands the plot like a pixel queen!

Remember, different displays or plot contexts may affect the appearance of your colors, hence always cross-verify during testing.

The deep well of matplotlib named colors

Matplotlib houses a wealth of colors hidden from plain view. Use matplotlib.colors._colors_full_map.values() to explore these.

Test and learn: the color game

Learning the art of coloring your plots is an iterative process. Try different named colors and observe how they pan out in your plots.