[Python | matplotlib] understanding and examples of matplotlib.cm

1. Module introduction

matplotlib.cmis a module in Matplotlib that provides a set of colormapfunctions 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, infernoetc.) and periodic color maps ( hsv, rainbow, jetetc.). 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.cmare 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.ListedColormapLinearSegmentedColormap

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

  1. 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()

insert image description here
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()

insert image description here
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()

insert image description here

No more examples for other colors!

Guess you like

Origin blog.csdn.net/wzk4869/article/details/130467948