【问题标题】:Extract matplotlib colormap in hex-format以十六进制格式提取 matplotlib 颜色图
【发布时间】:2016-02-09 08:28:32
【问题描述】:

我正在尝试通过操作 this example 从 matplotlib 颜色图中提取离散颜色。但是,我找不到从颜色图中提取的 N 离散颜色。

在下面的代码中我使用了cmap._segmentdata,但我发现它是整个颜色图的定义。给定一个颜色图和一个整数N,如何从颜色图中提取N 离散颜色并以十六进制格式导出?

from pylab import *

delta = 0.01
x = arange(-3.0, 3.0, delta)
y = arange(-3.0, 3.0, delta)
X,Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2 - Z1 # difference of Gaussians

cmap = cm.get_cmap('seismic', 5)    # PiYG
cmap_colors = cmap._segmentdata

def print_hex(r,b,g):
               if not(0 <= r <= 255 or 0 <= b <= 255 or 0 <= g <= 255):
                              raise ValueError('rgb not in range(256)')
               print '#%02x%02x%02x' % (r, b, g)


for i in range(len(cmap_colors['blue'])):
               r = int(cmap_colors['red'][i][2]*255)
               b = int(cmap_colors['blue'][i][2]*255)
               g = int(cmap_colors['green'][i][2]*255)
               print_hex(r, g, b)



im = imshow(Z, cmap=cmap, interpolation='bilinear',
            vmax=abs(Z).max(), vmin=-abs(Z).max())
axis('off')
colorbar()

show()

【问题讨论】:

    标签: python matplotlib hex color-mapping colormap


    【解决方案1】:

    您可以通过调用cmap(i) 来获取索引为i 的段的rgba 值元组。还有一个函数可以将 rgb 值转换为十六进制。正如 Joe Kington 在 cmets 中所写,您可以使用 matplotlib.colors.rgb2hex。因此,一个可能的解决方案是:

    from pylab import *
    
    cmap = cm.get_cmap('seismic', 5)    # PiYG
    
    for i in range(cmap.N):
        rgba = cmap(i)
        # rgb2hex accepts rgb or rgba
        print(matplotlib.colors.rgb2hex(rgba))
    

    输出是:

    #00004c
    #0000ff
    #ffffff
    #ff0000
    #7f0000
    

    【讨论】:

    • 或使用列表理解 [matplotlib.colors.rgb2hex(c) for c in cmap.colors]
    【解决方案2】:

    供将来参考:我的 CMasher 包提供了一个名为 take_cmap_colors() (https://cmasher.readthedocs.io/user/usage.html#taking-colormap-colors) 的函数,它允许从给定的颜色图中获取任意数量的离散颜色并以任何格式(8 位、标准化或十六进制)他们想要的。

    因此,例如,如果您想从 viridis 颜色图中以十六进制表示 5 种颜色,您可以这样做:

    import cmasher as cmr
    
    colors = cmr.take_cmap_colors('viridis', 5, return_fmt='hex')
    

    或者,如果您想要特定值范围内颜色图中的所有十六进制颜色,您可以这样做:

    colors = cmr.take_cmap_colors('viridis', None, cmap_range=(0.2, 0.8), return_fmt='hex')
    

    【讨论】:

      猜你喜欢
      • 2015-04-12
      • 2012-11-04
      • 2020-03-05
      • 2018-06-06
      • 1970-01-01
      • 2013-11-09
      • 1970-01-01
      • 2019-06-16
      • 2021-03-08
      相关资源
      最近更新 更多