Keywords: matplotlib | colors | python | visualization | named_colors
Abstract: This article explores the various named colors available in Matplotlib, including BASE_COLORS, CSS4_COLORS, XKCD_COLORS, and TABLEAU_COLORS. It provides detailed code examples for accessing and visualizing these colors, helping users enhance their plots with a wide range of color options. The guide also covers methods for using HTML hex codes and additional color prefixes, offering practical advice for data visualization.
Introduction
Matplotlib, a popular plotting library in Python, offers multiple ways to specify colors in plots, with named colors being a convenient option. However, many users are only familiar with a basic set of colors, overlooking the extensive collections available. This article provides an in-depth analysis of named colors in Matplotlib, covering everything from fundamental sets to expanded options, and includes code examples to help readers fully utilize these resources.
Overview of Color Sets
Matplotlib supports several named color collections, each with specific uses and origins:
- BASE_COLORS: A small set of basic colors represented by single-letter abbreviations such as 'b' for blue and 'g' for green, commonly used for quick plotting.
- CSS4_COLORS: A comprehensive set based on the CSS4 specification, including names like 'aliceblue' and 'antiquewhite', offering a wide range of color choices.
- XKCD_COLORS: Colors from the xkcd color survey, accessible via the 'xkcd:' prefix, e.g., 'xkcd:sky blue', with nearly 1000 colors suitable for diverse applications.
- TABLEAU_COLORS: Default colors from Tableau software, available with the 'tab:' prefix, such as 'tab:green', consisting of 10 distinct colors often used in business visualizations.
Additionally, colors can be specified using HTML hex codes, e.g., '#FF0000' for red, allowing for unlimited customization.
Code Examples for Accessing Named Colors
To retrieve the list of named colors in Matplotlib, use the matplotlib.colors module. The following code demonstrates how to print all color names and their hexadecimal values from the CSS4 set:
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
for name, hex in mcolors.CSS4_COLORS.items():
print(name, hex)This code iterates through the CSS4_COLORS dictionary and outputs each color name and hex value, enabling users to quickly review available options for their plots.
Visualizing Named Colors with a Color Table
For a better understanding of color sets, visualizing them through a color table is effective. The code below defines a function plot_colortable that sorts colors by HSV values and generates a chart with color samples and names:
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
import math
def plot_colortable(colors, ncols=4, sort_colors=True):
cell_width = 212
cell_height = 22
swatch_width = 48
margin = 12
if sort_colors:
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
for name, color in colors.items())
sorted_names = [name for hsv, name in by_hsv]
else:
sorted_names = list(colors.keys())
n = len(sorted_names)
nrows = math.ceil(n / ncols)
width = cell_width * ncols + 2 * margin
height = cell_height * nrows + 2 * margin
dpi = 72
fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi)
fig.subplots_adjust(left=margin/width, bottom=margin/height,
right=(width-margin)/width, top=(height-margin)/height)
ax.set_xlim(0, cell_width * ncols)
ax.set_ylim(cell_height * (nrows - 0.5), -cell_height / 2.0)
ax.set_axis_off()
for i, name in enumerate(sorted_names):
row = i % nrows
col = i // nrows
y = row * cell_height
swatch_start_x = cell_width * col
swatch_end_x = swatch_start_x + swatch_width
text_pos_x = swatch_start_x + swatch_width + 7
ax.text(text_pos_x, y, name, fontsize=14,
horizontalalignment='left', verticalalignment='center')
ax.hlines(y, swatch_start_x, swatch_end_x,
color=colors[name], linewidth=18)
return fig
# Example: Plot the CSS4 color set
fig = plot_colortable(mcolors.CSS4_COLORS)
plt.show()This function creates a table with color samples and names, grouped by similarity for easy browsing. Users can adjust parameters like the number of columns or sorting method to suit their visualization needs.
Using Additional Color Sets
Beyond standard sets, Matplotlib allows access to extra colors via prefixes. For example, using XKCD colors:
plt.plot([1, 2], lw=4, c='xkcd:baby poop green')Using Tableau colors:
plt.plot([1, 2], lw=4, c='tab:green')And using HTML hex codes:
plt.plot([1, 2], lw=4, c='#8f9805')These methods enhance color flexibility, enabling precise control over plot aesthetics. In practice, combining these options can lead to more engaging and informative visualizations.
Conclusion
Matplotlib provides a rich array of named colors through various collections and specification methods, from basic sets to expanded options like XKCD and Tableau colors, as well as custom hex codes. This guide's code examples and explanations aim to help users efficiently leverage these resources. It is recommended to experiment with different color combinations in practice to optimize visual impact. For more details, refer to the official Matplotlib documentation and source code.