Matplotlib 简明教程
Matplotlib - Colormaps
Colormap (通常称为颜色表或调色板),它是一组按照特定顺序排列的颜色,用于直观地表示数据。查看下方的图片以供参考 −
Colormap (often called a color table or a palette), is a set of colors arranged in a specific order, it is used to visually represent data. See the below image for reference −
在 Matplotlib 的上下文中,色彩图在各种绘图中将数值映射到颜色方面扮演着至关重要的角色。Matplotlib 提供内置色彩图和外部库(如 Palettable),甚至允许我们创建和操作我们自己的色彩图。
In the context of Matplotlib, colormaps play a crucial role in mapping numerical values to colors in various plots. Matplotlib offers built-in colormaps and external libraries like Palettable, or even it allows us to create and manipulate our own colormaps.
Colormaps in Matplotlib
Matplotlib 提供了许多内置色彩图,如“viridis”或“copper”,可通过 matplotlib.colormaps 容器访问它们。这是一个通用注册表实例,它返回一个色彩图对象。
Matplotlib provides number of built-in colormaps like 'viridis' or 'copper', those can be accessed through matplotlib.colormaps container. It is an universal registry instance, which returns a colormap object.
Example
以下示例获取 Matplotlib 中所有已注册色彩图的列表。
Following is the example that gets the list of all registered colormaps in matplotlib.
from matplotlib import colormaps
print(list(colormaps))
['magma', 'inferno', 'plasma', 'viridis', 'cividis', 'twilight', 'twilight_shifted', 'turbo', 'Blues', 'BrBG', 'BuGn', 'BuPu', 'CMRmap', 'GnBu', 'Greens', 'Greys', 'OrRd', 'Oranges', 'PRGn', 'PiYG', 'PuBu', 'PuBuGn', 'PuOr', 'PuRd', 'Purples', 'RdBu', 'RdGy', 'RdPu', 'RdYlBu', 'RdYlGn', 'Reds', 'Spectral', 'Wistia', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd', 'afmhot', 'autumn', 'binary', 'bone', 'brg', 'bwr', 'cool', 'coolwarm', 'copper', 'cubehelix', 'flag', 'gist_earth', 'gist_gray', 'gist_heat', 'gist_ncar', 'gist_rainbow', 'gist_stern', 'gist_yarg', 'gnuplot', 'gnuplot2', 'gray', 'hot', 'hsv', 'jet', 'nipy_spectral', 'ocean', …]
Accessing Colormaps and their Values
你可以使用 matplotlib.colormaps['viridis'] 获取一个已命名的色彩图,并且它返回一个色彩图对象。获取色彩图对象后, يمكنك通过对色彩图重新采样来访问其值。在本例中, viridis 是一个色彩图对象,当传递一个介于 0 和 1 之间浮点数时,它从色彩图返回一个 RGBA 值。
You can get a named colormap using matplotlib.colormaps['viridis'], and it returns a colormap object. After obtaining a colormap object, you can access its values by resampling the colormap. In this case, viridis is a colormap object, when passed a float between 0 and 1, it returns an RGBA value from the colormap.
Creating and Manipulating Colormaps
Matplotlib 提供创建或操作你自己的色彩图的灵活性。此过程涉及使用类 ListedColormap 或 LinearSegmentedColormap 。
Matplotlib provides the flexibility to create or manipulate your own colormaps. This process involves using the classes ListedColormap or LinearSegmentedColormap.
Creating Colormaps with ListedColormap
ListedColormaps 类通过提供颜色规范列表或数组来创建自定义色彩图非常有用。你可以使用它来使用颜色名称或 RGB 值构建新的色彩图。
The ListedColormaps class is useful for creating custom colormaps by providing a list or array of color specifications. You can use this to build a new colormap using color names or RGB values.
以下示例演示如何使用 ListedColormap 类和特定颜色名称创建自定义色彩图。
The following example demonstrates how to create custom colormaps using the ListedColormap class with specific color names.
import matplotlib as mpl
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import numpy as np
# Creating a ListedColormap from color names
colormaps = [ListedColormap(['rosybrown', 'gold', "crimson", "linen"])]
# Plotting examples
np.random.seed(19680801)
data = np.random.randn(30, 30)
n = len(colormaps)
fig, axs = plt.subplots(1, n, figsize=(7, 3), layout='constrained', squeeze=False)
for [ax, cmap] in zip(axs.flat, colormaps):
psm = ax.pcolormesh(data, cmap=cmap, rasterized=True, vmin=-4, vmax=4)
fig.colorbar(psm, ax=ax)
plt.show()
执行上述程序时,你将得到以下输出:
On executing the above program, you will get the following output −
Creating Colormaps with LinearSegmentedColormap
LinearSegmentedColormap 类通过指定锚点及其对应颜色允许更多控制。这允许创建具有插值值的色彩图。
The LinearSegmentedColormap class allows more control by specifying anchor points and their corresponding colors. This enables the creation of colormaps with interpolated values.
以下示例演示如何使用 LinearSegmentedColormap 类和特定颜色名称列表创建自定义色彩图。
The following example demonstrates how to create custom colormaps using the LinearSegmentedColormap class with a specific list of color names.
import matplotlib as mpl
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.pyplot as plt
import numpy as np
# Creating a LinearSegmentedColormap from a list
colors = ["rosybrown", "gold", "lawngreen", "linen"]
cmap_from_list = [LinearSegmentedColormap.from_list("SmoothCmap", colors)]
# Plotting examples
np.random.seed(19680801)
data = np.random.randn(30, 30)
n = len(cmap_from_list)
fig, axs = plt.subplots(1, n, figsize=(7, 3), layout='constrained', squeeze=False)
for [ax, cmap] in zip(axs.flat, cmap_from_list):
psm = ax.pcolormesh(data, cmap=cmap, rasterized=True, vmin=-4, vmax=4)
fig.colorbar(psm, ax=ax)
plt.show()
执行上述程序时,你将得到以下输出:
On executing the above program, you will get the following output −
Reversing Colormaps
可以通过使用 colormap.reversed() 方法来反转色彩图。这会创建一个新色彩图,该色彩图是原始色彩图的反转版本。
Reversing a colormap can be done by using the colormap.reversed() method. This creates a new colormap that is the reversed version of the original colormap.
此示例生成原始色彩图及其反转版本的并排可视化。
This example generates side-by-side visualizations of the original colormap and its reversed version.
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import numpy as np
# Define a list of color values in hexadecimal format
colors = ["#bbffcc", "#a1fab4", "#41b6c4", "#2c7fb8", "#25abf4"]
# Create a ListedColormap with the specified colors
my_cmap = ListedColormap(colors, name="my_cmap")
# Create a reversed version of the colormap
my_cmap_r = my_cmap.reversed()
# Define a helper function to plot data with associated colormap
def plot_examples(colormaps):
np.random.seed(19680801)
data = np.random.randn(30, 30)
n = len(colormaps)
fig, axs = plt.subplots(1, n, figsize=(n * 2 + 2, 3), layout='constrained', squeeze=False)
for [ax, cmap] in zip(axs.flat, colormaps):
psm = ax.pcolormesh(data, cmap=cmap, rasterized=True, vmin=-4, vmax=4)
fig.colorbar(psm, ax=ax)
plt.show()
# Plot the original and reversed colormaps
plot_examples([my_cmap, my_cmap_r])
执行上述程序时,你将得到以下输出:
On executing the above program, you will get the following output −
Changing the default colormap
要更改所有后续绘图的默认色彩图,你可以使用 mpl.rc() 来修改默认色彩图设置。
To change the default colormap for all subsequent plots, you can use mpl.rc() to modify the default colormap setting.
Example
这里有一个示例,通过修改全局 Matplotlib 设置来将默认色彩图更改为 RdYlBu_r ,如 mpl.rc('image', cmap='RdYlBu_r')。
Here is an example that changes the default colormap to RdYlBu_r by modifying the global Matplotlib settings like mpl.rc('image', cmap='RdYlBu_r').
import numpy as np
from matplotlib import pyplot as plt
import matplotlib as mpl
# Generate random data
data = np.random.rand(4, 4)
# Create a figure with two subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(7, 4))
# Plot the first subplot with the default colormap
ax1.imshow(data)
ax1.set_title("Default colormap")
# Set the default colormap globally to 'RdYlBu_r'
mpl.rc('image', cmap='RdYlBu_r')
# Plot the modified default colormap
ax2.imshow(data)
ax2.set_title("Modified default colormap")
# Display the figure with both subplots
plt.show()
执行上述代码,我们将得到以下输出 −
On executing the above code we will get the following output −
Plotting Lines with Colors through Colormap
要通过色彩图绘制具有不同颜色的多条线条,你可以使用 Matplotlib 的 plot() 函数以及一个色彩图来将不同颜色分配给每条线条。
To plot multiple lines with different colors through a colormap, you can utilize Matplotlib’s plot() function along with a colormap to assign different colors to each line.
Example
以下示例通过迭代范围并在 plot() 函数中使用 color 参数用来自色彩图的不同颜色绘制每条线条来绘制多条线条。
The following example plot multiple lines by iterating over a range and plotting each line with a different color from the colormap using the color parameter in the plot() function.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Generate x and y data
x = np.linspace(0, 2 * np.pi, 64)
y = np.exp(x)
# Plot the initial line
plt.plot(x, y)
# Define the number of lines and create a colormap
n = 20
colors = plt.cm.rainbow(np.linspace(0, 1, n))
# Plot multiple lines with different colors using a loop
for i in range(n):
plt.plot(x, i * y, color=colors[i])
plt.xlim(4, 6)
plt.show()
执行上述代码,我们将得到以下输出 −
On executing the above code we will get the following output −