当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Matplotlib.colors.to_hex()用法及代码示例


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

matplotlib.colors.to_hex()

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

用法: matplotlib.colors.to_hex(c, keep_alpha=False)


参数:

  1. c:这表示介于0到1之间的颜色序列数组。
  2. keep_alpha:如果设置为True,则使用#rrggbbaa格式,否则使用#rrggbb格式,并且仅接受布尔值。

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


输出:




相关用法


注:本文由纯净天空筛选整理自RajuKumar19大神的英文原创作品 Matplotlib.colors.to_hex() in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。