Extract matplotlib matrix in hexadecimal format

I am trying to extract discrete colors from collotap matplotlib by manipulating in this example . However, I cannot find the discrete colors N that are extracted from the color map.

In the code below, I used cmap._segmentdata , but I found that this is the definition of the entire color scheme. Given the colormap and integer N , how do I extract N discrete colors from a color map and export them in hex?

 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() 
+8
python matplotlib hex colormap color-mapping
source share
1 answer

You can get a tuple of rgba values ​​for a segment with index i by calling cmap(i) . There is already a function that turns rgb values ​​into hex. As Joe Kington wrote in the comments, you can use matplotlib.colors.rgb2hex . Therefore, a possible solution could be:

 from pylab import * cmap = cm.get_cmap('seismic', 5) # PiYG for i in range(cmap.N): rgb = cmap(i)[:3] # will return rgba, we take only first 3 so we get rgb print(matplotlib.colors.rgb2hex(rgb)) 

Output:

 #00004c #0000ff #ffffff #ff0000 #7f0000 
+14
source share

All Articles