Mastering Colormaps in Python: A Comprehensive Guide to Effective Data Visualization with Matplotlib (2026 Edition)
Introduction
As a data scientist or analyst, creating impactful visualizations is crucial for conveying insights from your data. The colors you choose can make or break your plots and dashboards. This is where colormaps come in. Colormaps, or "cmaps" for short, are a powerful tool in the Python plotting library Matplotlib for mapping numeric values to colors in a 2D plot or 3D surface. Effective use of cmaps allows you to visualize patterns, draw attention to important areas, and tell a story with your data.
In this in-depth guide, we‘ll dive into everything you need to know to master colormaps in Python. Whether you‘re a Matplotlib novice or a visualization veteran, you‘ll gain practical knowledge and inspiration to take your plots to the next level. We‘ll cover the different types of built-in colormaps, how to customize and create your own, best practices, and the latest features in colormaps as of 2024. Let‘s get started on our colorful journey!
Types of Built-in Colormaps
Matplotlib provides a rich collection of built-in colormaps to suit various visualization needs. Here‘s an overview of the main categories:
Sequential Colormaps
Sequential colormaps are used to represent data that has an ordering or progression, such as temperature, elevation, or time. The colors transition smoothly from low to high values. Some popular sequential colormaps include:
– viridis (default)
– plasma
– inferno
– magma
– cividis
Diverging Colormaps
Diverging colormaps are used when the data has a central neutral value and diverges in two opposite directions, such as positive/negative, gain/loss, or correlation coefficients. The colors transition from one hue for low values, to a neutral color in the middle, to the opposite hue for high values. Examples include:
– RdBu
– RdYlGn
– coolwarm
– PiYG
– BrBG
Cyclic Colormaps
Cyclic colormaps represent data that wraps around, such as angles, directions, or phases. The color at the beginning and end of the colormap are the same. Options include:
– twilight
– twilight_shifted
– hsv
Qualitative Colormaps
Qualitative colormaps are used for categorical data where there is no inherent ordering. Each category is assigned a distinct color. Some examples are:
– tab10
– Pastel1
– Set3
– Accent
Miscellaneous Colormaps
Matplotlib also provides a few specialty colormaps like:
– flag (country flags)
– prism (repeating sequence of colors)
– ocean (blue-green map)
– gist_earth (map of earth tones)
– gist_stern (black-yellow-white)
– gnuplot (black-blue-green-yellow-white)
No matter what type of data you‘re working with, matplotlib has a colormap to suit your needs. But the real power comes in being able to customize and create your own…
Applying Colormaps to Plots
Using an existing colormap in matplotlib is straightforward. Most plotting functions accept a "cmap" parameter where you can specify the name of the colormap to use. For example:
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
data = np.random.rand(100, 100)
# Apply the ‘plasma‘ colormap
plt.imshow(data, cmap=‘plasma‘)
plt.colorbar()
plt.show()
This will display a 2D grid of random values, colored using the ‘plasma‘ colormap, with a colorbar showing the mapping of values to colors.
You can apply colormaps to various types of plots, including:
- image plots (imshow)
- contour plots (contour, contourf)
- scatter plots (scatter)
- surface plots (plot_surface)
- histogram plots (hist2d)
- bar charts (bar, barh)
- polar charts (polar)
- and any plot that accepts a "color" parameter
Simply provide the name of the desired colormap, and matplotlib will take care of the rest.
To apply a colormap to subplots, you can use the fig.colorbar() function after creating the individual subplots:
# Create a 2x2 grid of subplots
fig, axs = plt.subplots(2, 2, figsize=(8, 8))
# Plot random data on each subplot with a different colormap
cmaps = [‘viridis‘, ‘plasma‘, ‘inferno‘, ‘magma‘]
for i in range(2):
for j in range(2):
data = np.random.rand(10, 10)
im = axs[i,j].imshow(data, cmap=cmaps[i*2+j])
fig.colorbar(im, ax=axs[i,j])
plt.tight_layout()
plt.show()
This will display a 2×2 grid of subplots, each with its own colorbar and colormap applied. Experiment with different colormaps to find the ones that work best for your specific data and message.
Creating and Customizing Colormaps
While the default colormaps are great, you may want to create your own custom colormaps to perfectly suit your visualization style and brand. Matplotlib allows you to do this in a few ways.
Modifying Existing Colormaps
One option is to take an existing colormap and modify certain properties, like the number of color levels, the color range, or reversing the order. Here‘s an example of creating a custom ‘inferno‘ colormap with only 5 color levels:
from matplotlib import cm
from matplotlib.colors import ListedColormap
# Get the ‘inferno‘ colormap with 5 levels
inferno_5 = cm.get_cmap(‘inferno‘, 5)
# Apply the custom colormap
plt.imshow(data, cmap=inferno_5)
plt.colorbar()
plt.show()
You can also extract a subset of an existing colormap by specifying the start and end points as a fraction between 0 and 1. For instance, to get the middle 50% of the ‘rainbow‘ colormap:
rainbow_middle = ListedColormap(cm.rainbow(np.linspace(0.25, 0.75, 256)))
This takes the portion of ‘rainbow‘ between 0.25 and 0.75 and generates a new colormap with 256 levels.
Combining Existing Colormaps
Another way to create custom colormaps is by combining two or more existing ones. This allows you to create diverging or multi-hue colormaps tailored to your data. For example, let‘s make a colormap that goes from dark red to light gray to deep blue:
from matplotlib.colors import LinearSegmentedColormap
# Get 128 color levels from each half
colors1 = cm.Reds_r(np.linspace(0, 1, 128))
colors2 = cm.Blues(np.linspace(0, 1, 128))
# Combine and create new colormap
colors = np.vstack((colors1, colors2))
red_blue = LinearSegmentedColormap.from_list(‘RedBlue‘, colors)
# Apply the custom colormap
plt.imshow(data, cmap=red_blue)
plt.colorbar()
plt.show()
This takes 128 color levels from the reversed ‘Reds‘ colormap for the lower half, 128 levels from the regular ‘Blues‘ colormap for the upper half, stacks them together, and creates a new ‘RedBlue‘ colormap from the result. The possibilities for combining existing colormaps are endless!
Making Colormaps from Scratch
For ultimate customization, you can define colormaps from scratch using specific colors in the RGB or HSV color spaces. This is useful for incorporating exact brand colors or palettes from tools like Coolors.co into your visualizations.
Here‘s an example of creating a bespoke blue-gold diverging colormap:
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
# Define RGB color values
colors = [‘#000063‘, ‘#0000C1‘, ‘#414BFC‘, ‘#FFDF3C‘, ‘#FFAB00‘]
# Create colormap
cmap = LinearSegmentedColormap.from_list(‘BlueGold‘, colors, N=256)
# Apply the custom colormap
plt.imshow(data, cmap=cmap)
plt.colorbar()
plt.show()
This takes a list of hex color codes, generates a smooth gradient between them, and creates a ‘BlueGold‘ colormap with 256 levels. You can use any valid color format, such as RGB tuples, hex strings, or X11/CSS4 color names. Have fun crafting colorful combinations!
Adjusting Colorbar Properties
The colorbar is a key element for interpreting colormapped plots. Matplotlib allows you to customize the colorbar‘s appearance and behavior to enhance your visualization:
orientation: Set to ‘vertical‘ (default) or ‘horizontal‘label: Provide a title or units for the colorbarticks: Specify the tick locationsformat: Set the format string for tick labelsextend: Indicate if the colorbar should have extension arrows for out-of-range values. Options are ‘neither‘ (default), ‘both‘, ‘min‘, ‘max‘.
For instance:
im = plt.imshow(data, cmap=‘viridis‘)
# Add a horizontal colorbar below the plot
cbar = plt.colorbar(im, orientation=‘horizontal‘, label=‘Intensity‘,
extend=‘both‘, format=‘%.1f‘)
# Set the tick locations and labels
cbar.set_ticks([0.2, 0.5, 0.8])
cbar.set_ticklabels([‘Low‘, ‘Medium‘, ‘High‘])
plt.show()
This adds a horizontal colorbar with a label, extension arrows on both ends to indicate values beyond the colormap limits, custom tick locations and labels, and formatted values. Spend time refining your colorbar to provide helpful information to viewers.
Colormap Best Practices
Choosing an effective colormap is both an art and a science. While the "best" colormap depends on the context and story you want to tell, here are some general guidelines:
- Use sequential colormaps for data with an inherent ordering or progression
- Use diverging colormaps for data with a meaningful middle point and two extremes
- Use qualitative colormaps for categorical data
- Avoid using the ‘jet‘ colormap, as research has shown it can distort and obscure patterns in the data
- Consider colorblind-friendly options like ‘viridis‘, ‘cividis‘, ‘inferno‘, ‘magma‘
- Aim for a perceptually uniform colormap where equal steps in data are perceived as equal steps in color
- Be mindful of the background color and ensure adequate contrast
- Don‘t rely solely on color to convey information; use annotations, labels, and other visual cues as well
With a little thought and intention, you can choose colormaps that faithfully represent the data and guide viewers to the key insights.
Comparing Matplotlib to Other Libraries
While Matplotlib is a popular and comprehensive library for data visualization in Python, it‘s not the only game in town. Other libraries also provide colormaps and plotting capabilities:
-
Seaborn: A statistical data visualization library built on top of matplotlib. Provides several attractive colormaps like ‘rocket‘, ‘mako‘, ‘icefire‘, and ‘vlag‘. Also includes color palettes for categorical data.
-
Plotly: An interactive graphing library that supports colormaps for various chart types. Offers a mix of matplotlib colormaps and its own options like ‘aggrnyl‘ (green-yellow), ‘bluered‘, and ‘plotly3‘.
-
Bokeh: A library for interactive visualization in web browsers. Provides a set of named colormaps as well as functions for creating custom ones from lists of colors or color palettes from tools like Color Brewer.
While each library has its own strengths and use cases, the concepts of colormaps remain consistent. Once you understand the basics in matplotlib, you can easily apply them to other plotting libraries and tools.
New in Matplotlib Colormaps (as of 2024)
Matplotlib continues to evolve and add new features with each release. Some of the latest colormap updates as of version 3.7 include:
-
New colormaps:
- ‘plasma‘: A sequential colormap that is perceptually uniform, colorblind-safe, and readable in grayscale. Designed to be a replacement for ‘jet‘.
- ‘cividis‘: A sequential colormap that is colorblind-safe, perceptually uniform, and designed for scientific visualization. Offers good contrast on both light and dark backgrounds.
- ‘twilight‘ and ‘twilight_shifted‘: Cyclic colormaps that provide a visually appealing transition between two contrasting colors. Useful for representing periodic data.
-
Colormap normalization: New classes for mapping data values to colormap elements, including
TwoSlopeNormfor emphasizing data extremes,FuncNormfor arbitrary normalization functions, andDivergingNormfor diverging data with asymmetric extents. -
Colormap registries: Ability to create and use separate colormap registries for different purposes or domains. Allows for easier management and avoids cluttering the global colormap list.
-
Improved colorbar annotations: More control over colorbar tick formatting and labels, including scientific notation, log scaling, and custom label positioning.
-
Enhanced colormap creation API: New functions for creating
ListedColormapandLinearSegmentedColormapinstances from color strings, tuples, or arrays. Simplifies custom colormap creation.
To stay up-to-date with the latest matplotlib features, check the official documentation, release notes, and examples gallery.
Learn More
We‘ve covered a lot of ground in this guide, but there‘s always more to learn and explore with colormaps in Python. Here are some additional resources to continue your journey:
- Matplotlib colormap reference: https://matplotlib.org/stable/gallery/color/colormap_reference.html
- Matplotlib colormap tutorial: https://matplotlib.org/stable/tutorials/colors/colormaps.html
- Seaborn color palettes: https://seaborn.pydata.org/tutorial/color_palettes.html
- SciPy colormaps: https://scipy-cookbook.readthedocs.io/items/Matplotlib_Show_colormaps.html
Remember, the best way to master colormaps is through practice and experimentation. Don‘t be afraid to try out different options, mix and match, and see what works best for your data and audience. With the knowledge and tools from this guide, you‘re well on your way to creating stunning, insightful visualizations with Python. Happy colormapping!
Conclusion
Colormaps are a powerful tool for enhancing the meaning and impact of your data visualizations with Python and Matplotlib. By understanding the different types of colormaps, how to apply them to various plots, and how to customize and create your own, you can take your plots from bland to brilliant. Keep the best practices and latest features in mind as you explore the wonderful world of colormaps. The right colors can make all the difference in telling a compelling story with your data.