Matplotlib 简明教程
Matplotlib - Colorbars
颜色条是图中使用的颜色刻度的可视表示。它从数据中的最小值显示到最大值的颜色刻度,帮助我们了解图中的颜色变化。
A colorbar is a visual representation of the color scale used in a plot. It displays the color scale from the minimum to the maximum values in the data, helping us understand the color variations in the plot.
在以下图片中,你可以看到一个用红色矩形突出显示的简单颜色条:
In the following image you can observe a simple colorbar that is highlighted with a red color rectangle −
Colorbars in Matplotlib
Matplotlib 库提供了一个用于处理颜色条的工具,包括它们的创建、放置和自定义。
The Matplotlib library provides a tool for working with colorbars, including their creation, placement, and customization.
matplotlib.colorbar 模块负责创建颜色条,但是可以使用 Figure.colorbar() 或其等效的 pyplot 包装 pyplot.colorbar() 函数创建颜色条。这些函数在内部使用 Colorbar 类以及 make_axes_gridspec (对于 GridSpec 定位轴)或 make_axes (对于非 GridSpec 定位轴)。
The matplotlib.colorbar module is responsible for creating colorbars, however a colorbar can be created using the Figure.colorbar() or its equivalent pyplot wrapper pyplot.colorbar() functions. These functions are internally uses the Colorbar class along with make_axes_gridspec (for GridSpec-positioned axes) or make_axes (for non-GridSpec-positioned axes).
而且,颜色条必须是一个“可映射的”(即 matplotlib.cm.ScalarMappable)对象,通常是通过 imshow() 函数生成的 AxesImage。如果你想要创建一个没有附加图像的颜色条,你可以使用没有关联数据的 ScalarMappable。
And a colorbar needs to be a "mappable" (i.e, matplotlib.cm.ScalarMappable) object typically an AxesImage generated via the imshow() function. If you want to create a colorbar without an attached image, you can instead use a ScalarMappable without an associated data.
Example 1
下面是一个创建水平颜色条的简单示例,它不使用 ScalarMappable 类附加的图。
Here is an simple example that creates a horizontal colorbar without an attached plotusing the ScalarMappable class.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
# Create a figure and axis for the colorbar
fig, ax = plt.subplots(figsize=(6, 1), constrained_layout=True)
# Define a colormap and normalization for the colorbar
cmap = mpl.cm.cool
norm = mpl.colors.Normalize(vmin=5, vmax=10)
# Create a ScalarMappable without associated data using the defined cmap and norm
scalar_mappable = mpl.cm.ScalarMappable(norm=norm, cmap=cmap)
# Add a horizontal colorbar to the figure
colorbar = fig.colorbar(scalar_mappable, cax=ax, orientation='horizontal', label='Some Units')
# Set the title and display the plot
plt.title('Basic Colorbar')
plt.show()
执行上述代码,我们将得到以下输出 −
On executing the above code we will get the following output −
Example 2
这是另一个使用 pyplot.colorbar() 函数和默认参数创建的简单颜色条示例。
Here is another example creates a simple colorbar for the plot using the pyplot.colorbar() function with default parameters.
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
data = np.random.random((10, 10))
# Create a plot with an image and a colorbar
fig, ax = plt.subplots(figsize=(7,4))
im = ax.imshow(data, cmap='viridis')
# Add a colorbar to the right of the image
cbar = plt.colorbar(im, ax=ax)
# Show the plot
plt.show()
print('Successfully drawn the colorbar...')
Successfully drawn the colorbar...
Automatic Colorbar Placement
颜色条的自动放置是一种简单的方法。它确保每个子图都有自己的颜色条,清楚地指明每个子图中图像数据的定量范围。
Automatic placement of colorbars is a straightforward approach. This ensures that each subplot has its own colorbar, providing a clear indication of the quantitative extent of the image data in each subplot.
Example
此示例演示了多个子图的自动颜色条放置。
This example demonstrates the automatic colorbar placement for multiple subplots.
import matplotlib.pyplot as plt
import numpy as np
# Create a 2x2 subplot grid
fig, axs = plt.subplots(1, 2, figsize=(7,3))
cmaps = ['magma', 'coolwarm']
# Add random data with different colormaps to each subplot
for col in range(2):
ax = axs[col]
pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1), cmap=cmaps[col])
# Add a colorbar for the each subplots
fig.colorbar(pcm, ax=ax, pad=0.03)
plt.show()
print('Successfully drawn the colorbar...')
Successfully placed the colorbar...
Manual Colorbar Placement
此方法允许我们在图表中明确地确定颜色条的位置和外观。当自动放置无法实现所需的布局时,这一点可能是必要的。
This approach allows us to explicitly determine the location and appearance of a colorbar in a plot. Which may be necessary when the automatic placement does not achieve the desired layout.
通过使用 inset_axes() 或 add_axes() 创建嵌入式轴,然后通过 cax 关键字参数将其分配给颜色条,用户可以获得所需的输出。
By creating inset axes, either using inset_axes() or add_axes(), and then assigning it to the colorbar through the cax keyword argument, users can get the desired output.
Example
以下是一个示例,演示了如何在图表中手动确定颜色条放置位置。
Here is an example that demonstrates how to determine the colorbar placement manually in a plot.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
# Generate random data points
npoints = 1000
x, y = np.random.normal(10, 2, (2, npoints))
# Create a subplot
fig, ax = plt.subplots(figsize=(7,4))
# Set title
plt.title('Manual Colorbar Placement')
# Draw the plot
hexbin_artist = ax.hexbin(x, y, gridsize=20, cmap='gray_r', edgecolor='white')
# Manually create an inset axes for the colorbar
cax = fig.add_axes([0.8, 0.15, 0.05, 0.3])
# Add a colorbar using the hexbin_artist and the manually created inset axes
colorbar = fig.colorbar(hexbin_artist, cax=cax)
# Display the plot
plt.show()
执行上述代码,我们将得到以下输出 −
On executing the above code we will get the following output −
Customizing Colorbars
颜色条的外观(包括刻度线、刻度线标签和标签)可以根据特定要求进行自定义。 Vertical 颜色条通常在 y 轴上具有这些元素,而 horizontal 颜色条则在 x 轴上显示这些元素。ticks 参数用于设置刻度线,而 format 参数用于设置可见颜色条轴上的刻度线标签的格式。
The appearance of colorbars, including ticks, tick labels, and labels, can be customized to specific requirements. Vertical colorbars typically have these elements on the y-axis, while horizontal colorbars display them on the x-axis. The ticks parameter is used to set the ticks, and the format parameter helps format the tick labels on the visible colorbar axes.
Example 1
此示例使用 imshow() 方法将数据显示为图像,并使用指定的标签将颜色条水平放置在图像中。
This example uses the imshow() method to display the data as an image, and places a colorbar horizontally to the image with a specified label.
import matplotlib.pyplot as plt
import numpy as np
# Create a subplot
fig, ax = plt.subplots(figsize=(7, 4))
# Generate random data
data = np.random.normal(size=(250, 250))
data = np.clip(data, -1, 1)
# Display the data using imshow with a specified colormap
cax = ax.imshow(data, cmap='afmhot')
ax.set_title('Horizontal Colorbar with Customizing Tick Labels')
# Add a horizontal colorbar and set its orientation and label
cbar = fig.colorbar(cax, orientation='horizontal', label='A colorbar label')
# Adjust ticks on the colorbar
cbar.set_ticks(ticks=[-1, 0, 1])
cbar.set_ticklabels(['Low', 'Medium', 'High'])
# Show the plot
plt.show()
执行上述代码,我们将得到以下输出 −
On executing the above code we will get the following output −
Example 2
此示例演示了如何自定义颜色条的位置、宽度、颜色、刻度线数量、字体大小以及更多属性。
This example demonstrates how to customize the position, width, color, number of ticks, font size and more properties of a colorbar.
import numpy as np
from matplotlib import pyplot as plt
# Adjust figure size and autolayout
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Generate random data
data = np.random.randn(4, 4)
# Plot the data with imshow
im = plt.imshow(data, interpolation='nearest', cmap="PuBuGn")
# Add colorbar and adjust its position
# Decrease colorbar width and shift position to the right
clb = plt.colorbar(im, shrink=0.9, pad=0.05)
# Set the top label for colorbar
clb.ax.set_title('Color Bar Title')
# Customize color of ticks
clb.ax.set_yticks([0, 1.5, 3, 4.5], labels=["A", "B", "C", "D"])
# Change color and font size of ticks
clb.ax.tick_params(labelcolor='red', labelsize=20)
plt.show()
执行上述代码时,您将获得以下输出 -
On executing the above code you will get the following output −