Hello programmers, we will discuss the Matplotlib cmap() in Python. First, the Matplotlib library has several built-in colormaps available via the cmap() function. Pyplot module of the Matplotlib library provides a MATLAB-like interface. Moreover, it helps to plot lines, contours, Histogram, bars, Scatter plots, 3D plots, etc.
The set_cmap() function in the pyplot module of the matplotlib library is used to set the default colormap that applies to the current image. In addition, colormaps are often split into several categories based on their function – sequential, diverging, qualitative, and cyclic. Before we cite examples of Matplotlib cmap(), let me briefly brief you about the function’s syntax and return type.
Syntax of Matplotlib cmap
syntax: matplotlib.pyplot.set_cmap(cmap)
Parameters
cmap: This cmap parameter is the colormap instance or the name of a registered colormap.
Return Type
Returns: This method does not return any value.
Example of Matplotlib cmap() in Python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm
dx, dy = 0.015, 0.05
x = np.arange(-4.0, 4.0, dx)
y = np.arange(-4.0, 4.0, dy)
X, Y = np.meshgrid(x, y)
extent = np.min(x), np.max(x), np.min(y), np.max(y)
Z1 = np.add.outer(range(8), range(8)) % 2
plt.imshow(Z1, cmap ="binary_r",
interpolation ='nearest',
extent = extent, alpha = 1)
def abc(x, y):
return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2))
Z2 = abc(X, Y)
plt.imshow(Z2, alpha = 0.7,
interpolation ='bilinear',
extent = extent)
plt.set_cmap("gist_rainbow")
plt.title('matplotlib.pyplot.set_cmap() Example')
plt.show()
Output:
Explanation:
Firstly, in the above example, a colormap is the plot created using set_cmap() method. This default colormap passed as an argument to the Matplotlib cmap() function applies to the current image. Finally, the ‘gist_rainbow ‘ passed to the cmap() function is a colormap instance of the LogNorm module imported from the Matplotlib.colors.
Sequential Colormaps
cmaps['Perceptually Uniform Sequential'] = [
'viridis', 'plasma', 'inferno', 'magma', 'cividis']
cmaps['Sequential'] = [
'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
'GnBu', 'PuBu']
Output:
Explanation:
Sequential cmaps() change in lightness and often saturation of color incrementally, often using a single hue. They are used for representing information that has order. Perpetual Uniform colormaps represent monotonically increasing lightness. And Sequential colormaps represent a change in a hue like ‘YlOrBr’ changes the shad of hue from Yellow to Orange to Brown. However, Perpetually Uniform colormaps are better than over sequential colormaps. Researchers have found that the human brain perceives changes in the lightness parameter as changes in data visualization much better than changes in hue.
Diverging Matplotlib cmap()
cmaps['Diverging'] = [
'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
'RdYlBu', 'RdYlGn', 'Spectral']
Output:
Explanation:
Matplotlib Diverging colormaps represent a change in lightness and possibly saturation of two different colors that meet in the middle at an unsaturated color. Used in python programs where the information has a critical middle value, such as topography or when the data deviates around zero. We need a monotonically increasing value of a hue followed by a decreasing value of the another for diverging colormaps.
Cyclic Matplotlib cmap()
cmaps['Cyclic'] = ['twilight', 'twilight_shifted', 'hsv']
Output:
Explanation:
Cyclic cmap() in Python represents a change in the lightness of two different colors that meet in the middle and beginning/end at an unsaturated color. These cyclic cmaps should be used for values that wrap around at the endpoints, such as phase angle, wind direction, or time of day.
Qualitatve Matplotlib cmap()
cmaps['Qualitative'] = ['Pastel1', 'Pastel2', 'Paired', 'Accent',
'Dark2', 'Set1', 'Set2', 'Set3']
Output:
Explanation:
Qualitative colormaps are often are miscellaneous colors. Moreover, they should be used to represent information that does not have ordering or relationships.
Miscellaneous Matplotlib cmap()
cmaps['Qualitative'] = ['flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',
'gist_rainbow', 'rainbow', 'jet', 'nipy_spectral', 'gist_ncar']
Output:
Explanation:
Miscellaneous colormaps allow you to create gradients and other interesting color palettes in Matplotlib. In addition, each of these strings are included in the code above.
Matplotlib Colormap Alpha
To specify values of alpha in colormap so that the colormap is not transparent, use the given syntax:
alphas = np.linspace(0, 1, cmap.N)
This will provide you with alphas in the given range and then inculcate it in your colormap. The range of alpha is from 0 to 1 here.
matplotlib colormap as list
colors =[ "orange", "blue", "red"]
cmap = matplotlib.colors.ListedColormap(colors)
You may use this to make a colormap from a list of colors. The ListedColormap changes colors in RGBA values. It will result in colormap objects.
Matplotlib Cmap Invert
To invert the spectrum, go for the given syntax:
Newcmap= matplotlib.cm.get_cmap('colormap title_r')
The ‘_r’ reverses the order in which colors appear in colormap.
reversed() function will also give similar results.
Matplotlib Cmap Transparent
You can set the alpha value to adjust transparency in cmap.
Use linspace for the same:
np.linspace(0, 1, cmap.N)
Or set the alpha value as 0 or 1 or between 0 and 1.
FAQs
viridis is the default colormap available in matplotlib.
Functions like get_cmap and set_cmap provide better visualization of data using colormaps. You can change a plot to colormap using these functions and then use show() function to see the output.
Example:
cmap = plt.get_cmap(‘hot’)
plt.set_cmap(cmap)
Conclusion
We learned about cmap() in python and its examples and discussed different ways of implementing colormaps in Python programs depending on the purpose. We also focused on the Qualitative, i.e., a miscellaneous case of Colormap implementation. Refer to this article in case of any queries regarding the Matplotlib cmap() function.
However, please let me know in the comment section below if you have any questions. I will try to help you as soon as possible.
Happy Pythoning!