📜  Python中的 Matplotlib.colors.to_hex()

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

Python中的 Matplotlib.colors.to_hex()

Matplotlib是Python中用于数组二维图的惊人可视化库。 Matplotlib 是一个基于 NumPy 数组构建的多平台数据可视化库,旨在与更广泛的 SciPy 堆栈配合使用。

matplotlib.colors.to_hex()

matplotlib.colors.to_hex()函数用于将 0 到 1 之间的数字转换为十六进制颜色代码。如果 keep_alpha 设置为 False(它也是默认值),则使用#rrggbb格式,否则使用#rrggbbaa

示例 1:

import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np
  
# dummy data to build the grid
data = np.random.rand(10, 10) * 20
  
# converting into hex color code
hex_color=matplotlib.colors.to_hex([ 0.47, 
                                    0.0, 
                                    1.0 ])
  
# create discrete colormap
cmap = colors.ListedColormap([hex_color, 
                              'green'])
  
bounds = [0,10,20]
norm = colors.BoundaryNorm(bounds, cmap.N)
  
fig, ax = plt.subplots()
ax.imshow(data, cmap=cmap, norm=norm)
  
# draw gridlines
ax.grid(which='major', axis='both', 
        linestyle='-', color='k',
        linewidth=2)
  
ax.set_xticks(np.arange(-.5, 10, 1));
ax.set_yticks(np.arange(-.5, 10, 1));
  
plt.show()

输出:

示例 2:

import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np
  
# dummy data to build the grid
data = np.random.rand(10, 10) * 20
  
# converting into hex color
# code with alpha set to True
hex_color = matplotlib.colors.to_hex([ 0.47,
                                      0.0, 
                                      1.0, 
                                      0.5 ],
                                     keep_alpha = True)
  
# create discrete colormap
cmap = colors.ListedColormap([hex_color, 
                              'red'])
  
bounds = [0, 10, 20]
norm = colors.BoundaryNorm(bounds, cmap.N)
  
fig, ax = plt.subplots()
ax.imshow(data, cmap = cmap, norm = norm)
  
# draw gridlines
ax.grid(which ='major', axis ='both', 
        linestyle ='-', color ='k', 
        linewidth = 2)
  
ax.set_xticks(np.arange(-.5, 10, 1));
ax.set_yticks(np.arange(-.5, 10, 1));
  
plt.show()


输出: