Matplotlib Colors - A Guide to mcolors
Last Updated :
09 Apr, 2025
Colors play a crucial role in data visualization, as they can enhance the readability of charts, encode data, and guide the audience through the narrative of the visualization. The matplotlib.colors module, often imported as mcolors, is a powerful toolkit for color manipulation and application in Matplotlib. This article delves into the capabilities of mcolors, highlighting how to leverage named colors and beyond for effective data storytelling.
Understanding matplotlib.colors (mcolors)
The matplotlib.colors module provides a vast range of options for defining and manipulating colors in plots. From predefined color names to the ability to create custom colormaps, mcolors are indispensable for anyone looking to customize the aesthetic appeal of their Matplotlib visualizations.
Matplotlib supports a comprehensive list of named colors, which can be extremely convenient for quickly setting colors in your plots. These named colors encompass a broad spectrum, from basic colors like "red", "blue", and "green" to more shades like "skyblue", "limegreen", and "tomato".
Plotting Matplotlib Colours List
To visualize the available named colors, you can plot a color table using Matplotlib. Here's an example function that creates such a table, displaying both the color names and their hexadecimal codes:
Python
import math
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib.patches import Rectangle
def plot_colortable(colors, *, ncols=4, sort_colors=True):
# Define dimensions for each color cell and margins
cell_width = 212
cell_height = 22
swatch_width = 48
margin = 12
# Sort colors by their HSV values (if sort_colors is True) for visual harmony
if sort_colors:
names = sorted(colors, key=lambda c: tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(c))))
else:
# Use colors in their original order
names = list(colors)
# Calculate the number of rows needed based
# on the number of colors and desired number of columns
n = len(names)
nrows = math.ceil(n / ncols)
# Calculate figure size based on the
# number of columns and rows, including margins
width = cell_width * ncols + 2 * margin
height = cell_height * nrows + 2 * margin
dpi = 72 # Set figure DPI
# Create figure and axis for drawing the color table
fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi)
fig.subplots_adjust(margin/width, margin/height, (width-margin)/width, (height-margin)/height)
ax.set_xlim(0, cell_width * ncols)
ax.set_ylim(cell_height * (nrows-0.5), -cell_height/2.)
ax.yaxis.set_visible(False) # Hide Y axis
ax.xaxis.set_visible(False) # Hide X axis
ax.set_axis_off() # Hide the axis border
# Add color swatches and names to the figure
for i, name in enumerate(names):
row = i % nrows
col = i // nrows
y = row * cell_height
swatch_start_x = cell_width * col # X position for the swatch
text_pos_x = cell_width * col + swatch_width + 7 # X position for the text
# Add the color name text next to the swatch
ax.text(text_pos_x, y, name, fontsize=14,
horizontalalignment='left',
verticalalignment='center')
# Add the color swatch
ax.add_patch(
Rectangle(xy=(swatch_start_x, y-9), width=swatch_width,
height=18, facecolor=colors[name], edgecolor='0.7')
)
return fig
# Example usage of the function
if __name__ == "__main__":
# Define a sample set of colors by their names and corresponding color codes
colors = {
'b': 'blue',
'g': 'green',
'r': 'red',
'c': 'cyan',
'm': 'magenta',
'y': 'yellow',
'k': 'black',
}
# Call the function to plot the color table with these colors
fig = plot_colortable(colors, ncols=3, sort_colors=False)
plt.show() # Display the plot
Output:

Matplotlib CSS Colors Plot
To extend the previous function to include CSS colors, we can use the CSS4_COLORS dictionary available in matplotlib.colors. This dictionary contains a large selection of color names that are valid CSS color names, mapped to their corresponding hexadecimal color codes.
Below is an updated version of the code that uses CSS colors. In this example, the plot_colortable function is called with mcolors.CSS4_COLORS, which contains the CSS color names and values:
Python
plot_colortable(mcolors.CSS4_COLORS, ncols=4, sort_colors=True)
plt.show()
Output:

Releated Article - matplotlib colours
Conclusion
The matplotlib.colors module is a versatile tool for enhancing the visual quality of Matplotlib plots. By using named colors and the ability to visualize these colors, you can quickly experiment with and apply various color schemes to your data visualizations. Whether you're a seasoned data scientist or a beginner in Python programming, mastering the use of colors in Matplotlib can significantly improve the clarity, aesthetics, and effectiveness of your plots.
Similar Reads
Matplotlib.colors.to_rgb() in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.colors.to_rgb() The matplotlib.colors.to_rgb() function is used convert c (i
3 min read
Matplotlib.colors.PowerNorm class in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.colors.PowerNor The matplotlib.colors.PowerNorm class belongs to the matplot
2 min read
Matplotlib.colors.to_rgba() in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.colors.to_rgba() The matplotlib.colors.to_rgba() function is used convert c(
3 min read
Matplotlib pyplot.colors()
In Python, we can plot graphs for visualization using the Matplotlib library. For integrating plots into applications, Matplotlib provides an API. Matplotlib has a module named pyplot which provides a MATLAB-like interface. Matplotlib Add ColorThis function is used to specify the color. It is a do-n
2 min read
Matplotlib.colors.to_hex() in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.colors.to_hex() The matplotlib.colors.to_hex() function is used to convert nu
2 min read
Matplotlib.colors.rgb_to_hsv() in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.colors.rgb_to_hsv() The matplotlib.colors.rgb_to_hsv() function belongs to th
2 min read
Matplotlib.colors.Normalize class in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.  matplotlib.colors.Normalize The matplotlib.colors.Normalize class belongs to the matpl
3 min read
Matplotlib.axes.Axes.pcolor() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
2 min read
Matplotlib.axes.Axes.pcolormesh() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
2 min read
Matplotlib.colors.hsv_to_rgb() in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.colors.hsv_to_rgb() The matplotlib.colors.hsv_to_rgb() function is used to co
2 min read