Get Started With Colormaps (Cmap) in Python for Data Visualization Using Matplotlib (Updated 2023)
Data science is a multidisciplinary field that uses machine learning algorithms to analyze and interpret vast amounts of data. The combination of data science and machine learning has revolutionized how organizations make decisions and improve their operations. Matplotlib is a popular library in the Python ecosystem for visualizing the results of machine learning algorithms in a visually appealing way. It is a multi-platform library that can play with many operating systems and was built in 2002 by John Hunter. Colormaps or Cmap in Python are generated using Matplotlib, which we will discuss in detail in this article.
“Matplotlib is a multi-platform library”
- Get introduced to Colormaps (Cmap) in Python.
- Familiarize yourself with the existing Colormaps in Matplotlib.
- Learn how to create and modify new and custom Cmaps in Python using Matplotlib.
If you need to learn the introduction to using Matplotlib, you can check out this tutorial-
Table of Contents
- What Are Colormaps (Cmaps) in Matplotlib?
- How to Create Subplots in Matplotlib and Apply Cmaps?
- How to Create New Colormaps (Cmap) in Python?
- How to Modify Colormaps (Cmap) in Python?
- How to Create Custom Colormaps (Cmap) in Python?
What Are Colormaps (Cmaps) in Matplotlib?
In visualizing the 3D plot, we need colormaps to differ and make some intuitions in 3D parameters. Scientifically, the human brain perceives various intuitions based on the different colors they see.
Nowadays, people have started to develop new Python packages with simpler and more modern styles than in Matplotlib, like Seaborn, Plotly, and even Pandas, using Matplotlib’s API wrappers. But, I think Matplotlib is still in many programmers’ hearts. Matplotlib is a popular data visualization library that provides several built-in colormaps and also allows users to create custom colormaps. This allows for greater control and customization of the colors used in their visualizations.
Python matplotlib provides some nice colormaps you can use, such as Sequential colormaps, Diverging colormaps, Cyclic colormaps, and Qualitative colormaps. For practical purposes, I will not be explaining the differences between them. I think it will be simpler if I show you the examples of each categorical colormaps in Matplotlib.
Here are some examples (not all) of Sequential colormaps.
Matplotlib will give you viridis as a default colormaps.
Then, next are the examples of Diverging, Cyclic, Qualitative, and Misc colormaps in Matplotlib.
How to Create Subplots in Matplotlib and Apply Cmaps?
Here is an example of code to create subplots in matplotlib and apply a fancy colormap to the figure:
import matplotlib.pyplot as plt import numpy as np # Create a 2x2 grid of subplots fig, axs = plt.subplots(2, 2, figsize=(10,10)) # Generate random dataset for each subplot for i in range(2): for j in range(2): data = np.random.randn(100) axs[i, j].hist(data, color='red', alpha=0.5) # Apply a fancy colormap to the figure cmap = plt.get_cmap('hot') plt.set_cmap(cmap) # Show the figure plt.show()
This code creates a 2×2 grid of subplots, generates random data for each subplot, and plots a histogram of the data using the
hist function. The subplots are then colored using a fancy colormap from the matplotlib library. In this example, the
hot colormap is applied to the figure using the
Here is another example code that uses the
rgba colormaps in matplotlib:
import matplotlib.pyplot as plt import numpy as np # Generate dataset for the plot x = np.linspace(-10, 10, 1000) y = np.sin(x) # Plot the data plt.plot(x, y, color='red') # Use the rdbu colormap to color the background plt.imshow(np.outer(np.ones(10), np.arange(100)), cmap='RdBu', extent=(-10, 10, -1, 1), alpha=0.2) # Add text to the plot using an rgba color plt.text(5, 0.5, 'Text in RGBA color', color=(0, 1, 0, 0.5), fontsize=16) # Show the plot plt.show()
The above code generates data for a plot and plots it using the
plot function. The background of the plot is then colored using the
rdbu color map and the
imshow function. The text is added to the plot using the
text function and an
rgba color, which allows you to specify the opacity of the color. Finally, the plot is displayed using the
show function. The
rgba is used to define the colors using the Red-Green-Blue-Alpha (RGBA) model. It is an extension of rgb() color values in CSS containing an alpha channel that specifies the transparency of color.
How to Create New Colormaps (Cmap) in Python?
Are you not interested in all of the provided colormaps? Or do you need other fancy colormaps? If yes, you need to read this article until the end. I will guide you through customizing and creating your own colormaps.
But before customizing it, I will show you an example of using colormaps. I used the ‘RdYlBu_r’ colormaps to visualize my data.
Let’s modify your own colormaps.
Firstly, we must create the mock data that will be visualized using this code.
The data variable is an array that consists of 100 x 100 random numbers from 0–10. You can check it by writing this code.
After that, we will show the mock data with a default colormap using the simple code below.
plt.figure(figsize=(7, 6))plt.pcolormesh(data) plt.colorbar()
The code will show you a figure like this.
As I mentioned, if you didn’t define the colormaps you used, you will get the default matplotlib colormaps. The default colormap name is ‘viridis’.
Next, I will change the colormaps from ‘viridis’ to ‘inferno’ colormaps with this code.
You will get the result like this.
How to Modify Colormaps (Cmap) in Python?
Now, to modify the colormaps, you need to import the following sublibraries in Matplotlib.
from matplotlib import cm from matplotlib.colors import ListedColormap,LinearSegmentedColormap
To modify the number of color classes in your colormaps, you can use this code
new_inferno = cm.get_cmap('inferno', 5)# visualize with the new_inferno colormaps plt.pcolormesh(data, cmap = new_inferno) plt.colorbar()
and will get a result like this:
Next is modifying the range of color in a colormap. I will give you an example in ‘hsv’ colormaps. You need to understand the range of colors using this figure.
If we want to use only green color (about 0.3) to blue color (0.7), we can use the following code.
# modified hsv in 256 color class hsv_modified = cm.get_cmap('hsv', 256)# create new hsv colormaps in range of 0.3 (green) to 0.7 (blue) newcmp = ListedColormap(hsv_modified(np.linspace(0.3, 0.7, 256)))# show figure plt.figure(figsize=(7, 6)) plt.pcolormesh(data, cmap = newcmp) plt.colorbar()
It will give you a figure like this:
The list of colors in matplotlib can be obtained by accessing the color map library of the matplotlib library. To get the list of colors, you can use the following code:
import matplotlib.pyplot as plt colors = plt.cm.colors.CSS4_COLORS print(colors)
This code will give you a list of all the colors available in CSS4 – a set of standardized color names used in web design. You can also access other color maps in matplotlib, such as
plt.cm.Bluesby specifying the desired color map when calling
How to Create Custom Colormaps (Cmap) in Python?
Custom colormaps can be created and used in Matplotlib to visualize data in a more informative and appealing way. Matplotlib provides various functions to create and modify colormaps, such as
ListedColormap, making it a flexible library for creating colormaps in a more customized way.
To create your own colormaps, there are at least two methods. First, you can combine two Sequential colormaps in Matplotlib. Second, you can choose and combine your favorite color in RGB to create colormaps.
We will give you a demo of combining two Sequential colormaps to create a new colormap. We want to combine ‘Oranges’ and ‘Blues.’
You can read this code carefully.
# define top and bottom colormaps top = cm.get_cmap('Oranges_r', 128) # r means reversed version bottom = cm.get_cmap('Blues', 128)# combine it all newcolors = np.vstack((top(np.linspace(0, 1, 128)), bottom(np.linspace(0, 1, 128))))# create a new colormaps with a name of OrangeBlue orange_blue = ListedColormap(newcolors, name='OrangeBlue')
If you visualize the mock data using ‘OrangeBlue’ colormaps, you will get a figure like this.
Next is creating a colormap from two different colors you like. In this case, I will try to create it from yellow and red, as shown in the following picture.
First, you need to create yellow colormaps
# create yellow colormapsN = 256yellow = np.ones((N, 4))yellow[:, 0] = np.linspace(255/256, 1, N) # R = 255 yellow[:, 1] = np.linspace(232/256, 1, N) # G = 232 yellow[:, 2] = np.linspace(11/256, 1, N) # B = 11yellow_cmp = ListedColormap(yellow)
and red colormaps
red = np.ones((N, 4))red[:, 0] = np.linspace(255/256, 1, N) red[:, 1] = np.linspace(0/256, 1, N) red[:, 2] = np.linspace(65/256, 1, N)red_cmp = ListedColormap(red)
The visualization of the yellow and red colormaps you have created is shown in the following picture.
After that, you can combine it using the previous methods.
newcolors2 = np.vstack((yellow_cmp(np.linspace(0, 1, 128)), red_cmp(np.linspace(1, 0, 128))))double = ListedColormap(newcolors2, name='double')plt.figure(figsize=(7, 6))plt.pcolormesh(data, cmap=double) plt.colorbar()
You will get a figure like this:
Using this code, you can also adjust the orientation, extent, and pad distance of the colormaps.
plt.figure(figsize=(6, 7))plt.pcolormesh(data, cmap = double) plt.colorbar(orientation = 'horizontal', label = 'My Favourite Colormaps', extend = 'both', pad = 0.1)
You will be shown a figure like this:
I hope this article has given you an insight into Colormaps (Cmap) in Python. You can use them to convert data into interesting infographics that can be easily read and understood visually. You can custom design the colors, gradients, etc., using Matplotlib and create numerous different images.
- Colormaps or Cmap in Python is a very useful tool for data visualization.
- Matlibpro comes with a number of built-in colormaps, such as sequential, diverging, cyclic, qualitative, miscellaneous, etc.
- You can modify these default Cmaps or create your own custom ones using Python.
Frequently Asked Questions
A. Sequential colormaps, Diverging colormaps, Cyclic colormaps, Qualitative colormaps, and Miscellaneous colormaps are the different colormaps available in matplotlib by default.
A. The default matplotlib colormap is called ‘viridis.’
A. Colourmaps help visualize data better by using graphical plotting techniques, making it easier and more interesting to read and understand.
Leave a Reply Your email address will not be published. Required fields are marked *