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”
Learning Objectives
If you need to learn the introduction to using Matplotlib, you can check out this tutorial- Data Visualization with Matplotlib — For Absolute Beginner Part I
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.
Matplotlib will give you viridis as a default colormaps.
Then, next are the examples of Diverging, Cyclic, Qualitative, and Misc colormaps in Matplotlib.
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.
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.
plt.pcolormesh(data, cmap='inferno')
You will get the result like this.
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:
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:
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.Blues
by specifying the desired color map when calling plt.cm.colors
.
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.’
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 picture shows the visualization of the yellow and red colormaps you have created.
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:
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:
Factors Affecting Colormap Selection:
Import libraries:
import matplotlib.pyplot as plt
Explore available colormaps:
plt.cm.get_cmapnames()
to see a list of available colormaps.Select a colormap:
cmap
argument of plotting functions (e.g., plt.imshow(data, cmap='viridis')
).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
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')
.
A. The context determines the best cmap in the matplotlib colormap, but “viridis” is highly recommended for its perceptual uniformity and accessibility.
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')
.
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()
.
Hey, it was really helpful to me! Thanks a lot.