Article directory
1. Module introduction
matplotlib.cm
is a module in Matplotlib that provides a set of colormap
functions and classes for working with colormaps ( ). Color mapping is a method of mapping values to colors, and is often used to make heat maps, contour maps, scatter maps, etc.
This module provides a variety of commonly used color maps, such as commonly used linear color maps ( viridis
, plasma
, inferno
etc.) and periodic color maps ( hsv
, rainbow
, jet
etc.). Users can choose different color mappings according to their needs and apply them to the drawn graphics.
In addition to the predefined colormaps, some functions, such as , etc., matplotlib.cm
are provided for customizing the colormap. Users can use these functions to create custom color maps according to their own needs and apply them to graphics.ListedColormap
LinearSegmentedColormap
2. Example of color
The matplotlib.cm module provides a series of colormap (colormap) functions, which can map values to colors and are often used in data visualization.
matplotlib.cm contains a variety of different colormaps (color mapping), commonly used colormaps include:
- viridis
- plasma
- inferno
- magma
- citizens
- jet
- rainbow
- coolwarm
- Greys
- Blues
- Greens
- Oranges
- Reds
You matplotlib.cm.get_cmap()
can obtain colormap
an instance of through the method, and use this instance to perform color mapping. For details, please refer to the official documentation of Matplotlib.
Here are some commonly used matplotlib.cm functions and their examples:
- viridis: A dark blue to yellow colormap, often used for temperature or flow field diagrams.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
z = np.sin(x) + np.cos(y)
fig, ax = plt.subplots()
im = ax.imshow(z, cmap='viridis')
fig.colorbar(im)
plt.show()
2. plasma: A color map from dark purple to bright yellow, often used for high-contrast data visualization.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
z = np.sin(x) + np.cos(y)
fig, ax = plt.subplots()
im = ax.imshow(z, cmap='plasma')
fig.colorbar(im)
plt.show()
3. cool: A color mapping from blue to cyan, often used for visualization of temperature changes.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
z = np.sin(x) + np.cos(y)
fig, ax = plt.subplots()
im = ax.imshow(z, cmap='cool')
fig.colorbar(im)
plt.show()
No more examples for other colors!