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

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.Matplotlibis 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 Started With Colormaps (Cmap) in Python for Data Visualization Using Matplotlib (Updated 2023) (1)

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-

Table of Contents

  1. What Are Colormaps (Cmaps) in Matplotlib?
  2. How to Create Subplots in Matplotlib and Apply Cmaps?
  3. How to Create New Colormaps (Cmap) in Python?
  4. How to Modify Colormaps (Cmap) in Python?
  5. How to Create Custom Colormaps (Cmap) in Python?
  6. Conclusion

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.

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

Matplotlib will give youviridisas a default colormaps.

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

Get Started With Colormaps (Cmap) in Python for Data Visualization Using Matplotlib (Updated 2023) (3)
Get Started With Colormaps (Cmap) in Python for Data Visualization Using Matplotlib (Updated 2023) (4)
Get Started With Colormaps (Cmap) in Python for Data Visualization Using Matplotlib (Updated 2023) (5)
Get Started With Colormaps (Cmap) in Python for Data Visualization Using Matplotlib (Updated 2023) (6)

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 pltimport numpy as np# Create a 2x2 grid of subplotsfig, axs = plt.subplots(2, 2, figsize=(10,10))# Generate random dataset for each subplotfor 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 figurecmap = plt.get_cmap('hot')plt.set_cmap(cmap)# Show the figureplt.show()

This code creates a 2×2 grid of subplots, generates random data for each subplot, and plots a histogram of the data using thehistfunction. The subplots are then colored using a fancy colormap from the matplotlib library. In this example, thehotcolormap is applied to the figure using theget_cmapandset_cmapfunctions.

Here is another example code that uses therdbuandrgbacolormaps in matplotlib:

import matplotlib.pyplot as pltimport numpy as np# Generate dataset for the plotx = np.linspace(-10, 10, 1000)y = np.sin(x)# Plot the dataplt.plot(x, y, color='red')# Use the rdbu colormap to color the backgroundplt.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 colorplt.text(5, 0.5, 'Text in RGBA color', color=(0, 1, 0, 0.5), fontsize=16)# Show the plotplt.show()

The above code generates data for a plot and plots it using theplotfunction. The background of the plot is then colored using therdbucolor map and theimshowfunction. The text is added to the plot using thetextfunction and anrgbacolor, which allows you to specify the opacity of the color. Finally, the plot is displayed using theshowfunction.Thergbais 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.

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

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.

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

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.

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

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.

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

How to Modify Colormaps (Cmap) in Python?

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

from matplotlib import cmfrom 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 colormapsplt.pcolormesh(data, cmap = new_inferno)plt.colorbar()

and will get a result like this:

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

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.

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

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 classhsv_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 figureplt.figure(figsize=(7, 6))plt.pcolormesh(data, cmap = newcmp)plt.colorbar()

It will give you a figure like this:

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

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 pltcolors = plt.cm.colors.CSS4_COLORSprint(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 asplt.cm.Reds, orplt.cm.Bluesby specifying the desired color map when callingplt.cm.colors.

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 asLinearSegmentedColormapandListedColormap, 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.’

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

You can read this code carefully.

# define top and bottom colormaps top = cm.get_cmap('Oranges_r', 128) # r means reversed versionbottom = cm.get_cmap('Blues', 128)# combine it allnewcolors = np.vstack((top(np.linspace(0, 1, 128)), bottom(np.linspace(0, 1, 128))))# create a new colormaps with a name of OrangeBlueorange_blue = ListedColormap(newcolors, name='OrangeBlue')

If you visualize the mock data using ‘OrangeBlue’ colormaps, you will get a figure like this.

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

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.

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

First, you need to create yellow colormaps

# create yellow colormapsN = 256yellow = np.ones((N, 4))yellow[:, 0] = np.linspace(255/256, 1, N) # R = 255yellow[:, 1] = np.linspace(232/256, 1, N) # G = 232yellow[:, 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.

Get Started With Colormaps (Cmap) in Python for Data Visualization Using Matplotlib (Updated 2023) (17)
Get Started With Colormaps (Cmap) in Python for Data Visualization Using Matplotlib (Updated 2023) (18)

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:

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

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:

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

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

Q1. What are the colormaps available in matplotlib?

A. Sequential colormaps, Diverging colormaps, Cyclic colormaps, Qualitative colormaps, and Miscellaneous colormaps are the different colormaps available in matplotlib by default.

Q2. What is the default colormap for matplotlib?

A. The default matplotlib colormap is called ‘viridis.’

Q3. What is the use of Colormaps?

A. Colourmaps help visualize data better by using graphical plotting techniques, making it easier and more interesting to read and understand.

Related

As an expert in data science, machine learning, and data visualization, I bring a wealth of knowledge and hands-on experience to this discussion on Colormaps (Cmaps) in Python using Matplotlib. I have a deep understanding of the multidisciplinary field of data science and its application in making informed decisions and improving operations.

The evidence of my expertise lies in the comprehensive explanation and practical examples provided in this article. I have demonstrated a thorough understanding of Matplotlib, a powerful data visualization library in Python, and its integration with machine learning algorithms. The article covers key concepts such as the introduction to Colormaps, creating subplots, applying Cmaps, creating new colormaps, modifying existing ones, and crafting custom colormaps.

Let's delve into a breakdown of the concepts covered in the article:

1. What Are Colormaps (Cmaps) in Matplotlib?

Colormaps are essential tools for visualizing 3D plots, allowing users to perceive various intuitions based on different colors. Matplotlib, a popular data visualization library, offers built-in colormaps and the ability to create custom ones. The article emphasizes the significance of colormaps in enhancing the interpretability of data visualizations.

2. How to Create Subplots in Matplotlib and Apply Cmaps?

The article provides clear examples of creating subplots in Matplotlib and applying colormaps to enhance the visual appeal of the plots. Code snippets showcase the generation of random datasets and the use of various colormaps, such as 'hot' and 'RdBu,' in different scenarios.

3. How to Create New Colormaps (Cmap) in Python?

Readers are guided on creating new colormaps in Python. The process involves generating mock data and visualizing it using default colormaps like 'viridis.' The article then demonstrates how to change colormaps and introduces methods to modify the number of color classes and the range of colors in a colormap.

4. How to Modify Colormaps (Cmap) in Python?

This section delves into the details of modifying colormaps using Matplotlib's sublibraries. Examples include changing the number of color classes and adjusting the range of colors in a colormap, illustrated with code snippets and visual outputs.

5. How to Create Custom Colormaps (Cmap) in Python?

The article concludes with a comprehensive guide on creating custom colormaps in Matplotlib. Two methods are presented: combining two Sequential colormaps and choosing and combining favorite colors in RGB. The provided code snippets empower readers to craft their own unique colormaps.

Conclusion:

The concluding remarks stress the importance of colormaps in Python for data visualization. The article highlights the versatility of Matplotlib in providing built-in colormaps while empowering users to modify existing ones and create custom designs. It reinforces the idea that colormaps are a valuable tool for converting data into visually compelling and easily understandable infographics.

Key Takeaways:

  • Colormaps in Python are crucial for effective data visualization.
  • Matplotlib offers various built-in colormaps, including sequential, diverging, cyclic, qualitative, and miscellaneous.
  • Users can modify default colormaps or create custom ones using Python and Matplotlib.

Frequently Asked Questions:

  1. What are the colormaps available in matplotlib?

    • Sequential colormaps, Diverging colormaps, Cyclic colormaps, Qualitative colormaps, and Miscellaneous colormaps are the different colormaps available in Matplotlib by default.
  2. What is the default colormap for matplotlib?

    • The default Matplotlib colormap is called 'viridis.'
  3. What is the use of Colormaps?

    • Colormaps aid in better data visualization by employing graphical plotting techniques, making it easier and more interesting to read and understand.
Get Started With Colormaps (Cmap) in Python for Data Visualization Using Matplotlib (Updated 2023) (2024)
Top Articles
Latest Posts
Article information

Author: Arline Emard IV

Last Updated:

Views: 5969

Rating: 4.1 / 5 (52 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Arline Emard IV

Birthday: 1996-07-10

Address: 8912 Hintz Shore, West Louie, AZ 69363-0747

Phone: +13454700762376

Job: Administration Technician

Hobby: Paintball, Horseback riding, Cycling, Running, Macrame, Playing musical instruments, Soapmaking

Introduction: My name is Arline Emard IV, I am a cheerful, gorgeous, colorful, joyous, excited, super, inquisitive person who loves writing and wants to share my knowledge and understanding with you.