Python中的 Matplotlib.figure.Figure.colorbar()
Matplotlib是Python中的一个库,它是 NumPy 库的数值数学扩展。 figure 模块提供了顶级 Artist,即 Figure,其中包含所有绘图元素。该模块用于控制所有绘图元素的子图和顶级容器的默认间距。
matplotlib.figure.Figure.colorbar()函数
matplotlib 库的图形模块的 colorbar() 方法用于将颜色条添加到绘图中。
Syntax: colorbar(self, mappable, cax=None, ax=None, use_gridspec=True, **kw)
Parameters: This accept the following parameters that are described below:
- mappable: This parameter is mandatory for the Figure.colorbar method.
- cax : This parameter is the Axes into which the colorbar will be drawn.
- ax : This parameter is the parent axes from which space for a new colorbar axes will be stolen.
- use_gridspec : This parameter is used to create an instance of Subplot using the gridspec module.
Returns: This method does not return any value.
下面的示例说明了 matplotlib.figure 中的 matplotlib.figure.Figure.colorbar()函数:
示例 1:
# Implementation of matplotlib function
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
import numpy as np
# Create triangulation.
x = np.asarray([0, 1, 2, 3, 0.5,
1.5, 2.5, 1, 2,
1.5])
y = np.asarray([0, 0, 0, 0, 1.0,
1.0, 1.0, 2, 2,
3.0])
triangles = [[0, 1, 4], [1, 5, 4],
[2, 6, 5], [4, 5, 7],
[5, 6, 8], [5, 8, 7],
[7, 8, 9], [1, 2, 5],
[2, 3, 6]]
triang = mtri.Triangulation(x, y, triangles)
z = np.cos(3 * x) * np.cos(6 * y)+np.sin(6 * x)
fig, axs = plt.subplots()
t = axs.tricontourf(triang, z)
axs.tricontour(triang, z, colors ='white')
fig.colorbar(t)
fig.suptitle('matplotlib.figure.Figure.colorbar() \
function Example\n\n', fontweight ="bold")
plt.show()
输出:
示例 2:
# Implementation of matplotlib function
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
n_angles = 26
n_radii = 10
min_radius = 0.35
radii = np.linspace(min_radius,
0.95,
n_radii)
angles = np.linspace(0, 2 * np.pi,
n_angles,
endpoint = False)
angles = np.repeat(angles[..., np.newaxis],
n_radii,
axis = 1)
angles[:, 1::2] += np.pi / n_angles
x = (10 * radii * np.cos(angles)).flatten()
y = (10 * radii * np.sin(angles)).flatten()
z = (np.cos(4 * radii) * np.cos(3 * angles)).flatten()
triang = tri.Triangulation(x, y)
triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1),
y[triang.triangles].mean(axis = 1))
< min_radius)
fig1, ax1 = plt.subplots()
ax1.set_aspect('equal')
tcf = ax1.tricontourf(triang, z)
fig1.colorbar(tcf)
ax1.tricontour(triang, z, colors ='g')
fig1.suptitle('matplotlib.figure.Figure.colorbar()\
function Example\n\n', fontweight ="bold")
plt.show()
输出: