📜  Python中的 Matplotlib.colors.from_levels_and_colors()

📅  最后修改于: 2022-05-13 01:55:06.005000             🧑  作者: Mango

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 的级别和颜色参数。

示例 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()

输出: