Python中的 Matplotlib.colors.from_levels_and_colors()
Matplotlib是Python中用于数组二维图的惊人可视化库。 Matplotlib 是一个基于 NumPy 数组构建的多平台数据可视化库,旨在与更广泛的 SciPy 堆栈配合使用。
matplotlib.colors.from_levels_and_colors()
matplotlib.colors.from_levels_and_colors()
函数是帮助创建 cmap 和 norm 实例的辅助函数,其行为类似于 contourf 的级别和颜色参数。
Syntax: matplotlib.colors.from_levels_and_colors(levels, colors, extend=’neither’)
Parameters:
- levels: It is a sequence of numbers that represent quantization levels that are used to construct the BoundaryNorm. A value v is quantized to level k if lev[k] <= v < lev[k+1].
- colors: It is a sequence of colors that are used as fill colors for each level. There must be n_level – 1 colors if extend is “neither”. Add one extra color for an extend of “min” or “max” and for an extend of “both” add two colors.
- extend: It is an optional parameter that accepts one of the four values namely ‘neither’, ‘min’, ‘max’ or ‘both’.
Return Type : This function returns a Normalized cmap and a colormap norm
示例 1:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
data1 = 3 * np.random.random((10, 10))
data2 = 5 * np.random.random((10, 10))
levels = [0, 1, 2, 3, 4, 5]
colors = ['red', 'brown',
'yellow', 'green',
'blue']
cmap, norm = matplotlib.colors.from_levels_and_colors(levels,
colors)
fig, axes = plt.subplots(ncols = 2)
for ax, dat in zip(axes, [data1, data2]):
im = ax.imshow(dat,
cmap = cmap,
norm = norm,
interpolation ='none')
fig.colorbar(im, ax = ax, orientation ='horizontal')
plt.show()
输出:
示例 2:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import from_levels_and_colors
nvals = np.random.randint(2, 20)
data = np.random.randint(0, nvals,
(10, 10))
colors = np.random.random((nvals, 3))
# Make the colors pastels...
colors = colors / 2.5 + 0.55
levels = np.arange(nvals + 1) - 0.5
cmap, norm = from_levels_and_colors(levels,
colors)
fig, ax = plt.subplots()
im = ax.imshow(data,
interpolation ='nearest',
cmap = cmap,
norm = norm)
fig.colorbar(im, ticks = np.arange(nvals))
plt.show()
输出: