Get Started With Colormaps (Cmap) in Python for Data Visualization Using Matplotlib (Updated 2024)

guest_blog 11 Jun, 2024
9 min read

Introduction

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 colormaps ecosystem for visualizing the results of machine learning algorithms in a visually appealing way. John Hunter built this multi-platform library in 2002, which can play with many operating systems. In this article, we will discuss how Matplotlib colormaps generate colormaps or Cmap in Python in detail.

“Matplotlib is a multi-platform library”

Colormaps Matplotlib Python,cmap in python

Learning Objectives

  • 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-

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, developers are exploring new Python packages with modern styles such as Seaborn, Plotly, and even Pandas, while Matplotlib, with its enduring appeal, remains in many programmers’ hearts. Matplotlib, a widely-used data visualization library, offers numerous built-in colormaps. It also empowers users to craft custom colormaps, granting enhanced control and flexibility over the color schemes in their visualizations, a valuable feature when considering cmap in python colormaps.

Python matplotlib colormaps 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 matplotlib colormap.

Here are some examples (not all) of Sequential colormaps.

Perpetually uniform sequential Colormaps in Matplotlib [cmap python]

Matplotlib will give you viridis as a default colormaps.

Then, next are the examples of Diverging, Cyclic, Qualitative, and Misc colormaps in Matplotlib.

Miscellaneous colormaps in Matplotlib [cmap python]
Qualitative colormaps in Matplotlib [cmap python]
Cyclic colormaps in Matplotlib [cmap python]
Diverging colormaps in Matplotlib [cmap python]

How to Create Subplots in Matplotlib and Apply Cmaps?

Here is an example of code to create subplots in matplotlib colormaps 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 get_cmap and set_cmap functions.

Here is another example code that uses the rdbu and 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.

Example of RdYlBu_r colormaps in Matplotlib | cmap python

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.

mock data to be visualized

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.

colormesh of visualized mock data | cmap python

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.

plt.pcolormesh(data, cmap='inferno')

You will get the result like this.

colormesh of visualized inferno colormaps | cmap python

How to Modify Colormaps (Cmap) in Python?

Now, to modify the colormaps, you need to import the following sublibraries in matplotlib colormap.

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:

modified inferno colormaps | cmap python

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.

Color range for hsv colormaps [cmap python]

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:

modified inferno colormaps | cmap python

You can obtain the list of colors in matplotlib 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.Reds, or plt.cm.Bluesby specifying the desired color map when calling plt.cm.colors.

How to Create Custom Colormaps (Cmap) in Python?

You can create and use custom colormaps in Matplotlib to visualize data in a more informative and appealing way.. Matplotlib provides various functions to create and modify colormaps, such as LinearSegmentedColormap and 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 colormap. 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.’

Combining colormaps in matplotlib [cmap python]

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.

Modified combined colormaps in matplotlib | cmap python

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.

combining colormaps in matplotlib [cmap python]

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 picture shows the visualization of the yellow and red colormaps you have created.

red colormap in Matplotlib | cmap python
yellow colormap in Matplotlib | cmap python

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:

combined custimized colormaps in matplotlib | cmap python

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:

create and modify your own colormaps in matplotlib | cmap python

How to Choose colormaps in matplotlib?

Choosing a good colormap in matplotlib is essential for effectively conveying information in your data visualization. Here are some key points to consider:

Understanding Colormaps:

  • Colormaps represent data values using a sequence of colors.
  • The choice of colormap impacts how viewers interpret the data’s magnitude or categories.

Factors Affecting Colormap Selection:

  1. Data Type:
    • Sequential Data: Represents a single variable with a range of values (e.g., temperature). Use colormaps with monotonic lightness change (e.g., “viridis”, “plasma”).
    • Diverging Data: Represents values deviating from a central point (e.g., elevation). Use diverging colormaps with a central neutral color (e.g., “RdBu_r”, “bwr”).
    • Categorical Data: Represents distinct categories. Use colormaps with visually distinct colors (e.g., “tab10”, “Set1”).
  2. Colorblind-friendliness: Consider using colormaps designed for viewers with color blindness (e.g., “viridis”, “plasma”, colormaps from “colorcet” library).
  3. Field Standards: If your field has established colormap conventions, using those can improve clarity for viewers familiar with the domain.
  4. Audience Perception: Consider how viewers will interpret the colors. For example, many cultures associate red with hot and blue with cold.

Choosing a Colormap in matplotlib:

Import libraries:

import matplotlib.pyplot as plt

Explore available colormaps:

  • Use plt.cm.get_cmapnames() to see a list of available colormaps.

Select a colormap:

  • Assign the desired colormap name to cmap argument of plotting functions (e.g., plt.imshow(data, cmap='viridis')).

Conclusion

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.

Key Takeaways

  • Colormaps or Cmap in python colormaps 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 colormaps.

Frequently Asked Questions

Q1. How to set cmap in Matplotlib?

A. To set a colormap (cmap) in Matplotlib, use the cmap parameter in plotting functions like plt.scatter() or plt.imshow(), e.g., plt.imshow(data, cmap='viridis').

Q2. Which CMAP is best in Matplotlib?

A. The context determines the best cmap in the matplotlib colormap, but “viridis” is highly recommended for its perceptual uniformity and accessibility.

Q3. What is CMAP in Imshow?

A. In imshow(), cmap specifies the colormap for mapping scalar data to colors, enhancing visual representation of the data, e.g., plt.imshow(data, cmap='hot').

Q4. How to use color maps in Matplotlib?

A. To use color maps in Matplotlib, import cm from matplotlib, then apply a colormap using the cmap parameter in your plotting functions, like plt.plot() or plt.scatter().

guest_blog 11 Jun, 2024

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear

Yoojay
Yoojay 01 May, 2021

Hey, it was really helpful to me! Thanks a lot.