我们从Python开源项目中,提取了以下30个代码示例,用于说明如何使用matplotlib.colors.LinearSegmentedColormap()。
def add_cmap(name, cdict): """ Adds a colormap to the colormaps available in yt for this session """ yt_colormaps[name] = \ cc.LinearSegmentedColormap(name,cdict,256) mcm.datad[name] = cdict mcm.__dict__[name] = cdict try: # API compatibility mcm.register_cmap(name, yt_colormaps[name]) except AttributeError: pass # The format is as follows: # First number is the number at which we are defining a color breakpoint # Second number is the (0..1) number to interpolate to when coming *from below* # Third number is the (0..1) number to interpolate to when coming *from above* # Next up is boilerplate -- the name, the colormap dict we just made, and the # number of segments we want. This is probably fine as is.
def _cmap_discretize(cmap, N): """Return a discrete colormap from the continuous colormap cmap. cmap: colormap instance, eg. cm.jet. N: number of colors. Example x = resize(arange(100), (5,100)) djet = cmap_discretize(cm.jet, 5) imshow(x, cmap=djet) """ if type(cmap) == str: cmap = plt.get_cmap(cmap) colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.))) colors_rgba = cmap(colors_i) indices = np.linspace(0, 1., N+1) cdict = {} for ki, key in enumerate(('red','green','blue')): cdict[key] = [(indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki]) for i in range(N+1)] # Return colormap object. return mcolors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)
def setColorMapList(self, colormapList): """ Set color map list from browser """ self.standardColorMaps = [] self.cmapListCBox.blockSignals(True) # Block signal fo QComboBox for colormap in colormapList: # Check if it is a LinearSegmentedColormap. # If a user added the colormap it is LinearSegmentedColormap # otherwise a string if isinstance(colormapList[colormap], mplColors.LinearSegmentedColormap): # Find index in QComboBox idx = self.cmapListCBox.findText(colormapList[colormap].name, Qt.MatchExactly) # Only add when this colormap when it is not present in QComboBox if idx == -1: colorInfo = segmentDataColorMapToColorInfo(colormapList[colormap]) self.userColorMaps[colormapList[colormap].name] = colorInfo self.cmapListCBox.addItem(colormapList[colormap].name) else: self.standardColorMaps.append(colormapList[colormap]) self.cmapListCBox.blockSignals(False)
def split_colormap(self, colormap, n): """splits map by colour Args: colormap: chloropleth map n: colours Returns: portion of split map """ if type(colormap) == str: colormap = cm.get_cmap(colormap) colors = np.concatenate((np.linspace(0, 1., n), (0., 0., 0., 0.))) rgb_alpha = colormap(colors) indices = np.linspace(0, 1., n + 1) color_dict = {} for color, key in enumerate(('red', 'green', 'blue')): color_dict[key] = [(indices[i], rgb_alpha[i - 1, color], rgb_alpha[i, color]) for i in range(n + 1)] return LinearSegmentedColormap(colormap.name + "_%d" % n, color_dict, 1024)
def cmap_discretize(cmap, N): """ Return a discrete colormap from the continuous colormap cmap. cmap: colormap instance, eg. cm.jet. N: number of colors. Example x = resize(arange(100), (5,100)) djet = cmap_discretize(cm.jet, 5) imshow(x, cmap=djet) """ if type(cmap) == str: cmap = get_cmap(cmap) colors_i = np.concatenate((np.linspace(0, 1., N), (0., 0., 0., 0.))) colors_rgba = cmap(colors_i) indices = np.linspace(0, 1., N + 1) cdict = {} for ki, key in enumerate(('red', 'green', 'blue')): cdict[key] = [(indices[i], colors_rgba[i - 1, ki], colors_rgba[i, ki]) for i in xrange(N + 1)] return LinearSegmentedColormap(cmap.name + "_%d" % N, cdict, 1024)
def make_colormap(seq): """Return a LinearSegmentedColormap seq: a sequence of floats and RGB-tuples. The floats should be increasing and in the interval (0,1). """ seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3] cdict = {'red': [], 'green': [], 'blue': []} for i, item in enumerate(seq): if isinstance(item, float): r1, g1, b1 = seq[i - 1] r2, g2, b2 = seq[i + 1] cdict['red'].append([item, r1, r2]) cdict['green'].append([item, g1, g2]) cdict['blue'].append([item, b1, b2]) return mcolors.LinearSegmentedColormap('CustomMap', cdict,5000)
def _string_to_cmap(cm_name): """Return colormap given name. Parameters: cm_name (str): Name of colormap. Returns: `matplotlib.cm <http://matplotlib.org/api/cm_api.html>`_ (colormap) object """ if isinstance(cm_name, str): if 'linearlab' in cm_name: try: cmap, cmap_r = linearlab() except IOError: cmap = cm.viridis else: if '_r' in cm_name: cmap = cmap_r else: cmap = cm.get_cmap(cm_name) elif isinstance(cm_name, ListedColormap) or isinstance(cm_name, LinearSegmentedColormap): cmap = cm_name else: raise MarvinError('{} is not a valid cmap'.format(cm_name)) return cmap
def surface_plot(figure,X,Y,Z,color1,color2=None,xlabel="",ylabel="",zlabel="",alpha=1.0,linewidth=3,label=""): from mpl_toolkits.mplot3d import axes3d from matplotlib.colors import LinearSegmentedColormap if color2 is None: color2 = color1 cdict = {'red': ((0.0, color1[0], color1[0]),(1.0, color2[0], color2[0])), 'green': ((0.0, color1[1], color1[1]),(1.0, color2[1], color2[1])), 'blue': ((0.0, color1[2], color1[2]),(1.0, color2[2], color2[2]))} cmap = LinearSegmentedColormap('CMap', cdict) font = fm.FontProperties(family = 'Trebuchet', weight ='light') figure.patch.set_facecolor('white') axes = figure.add_subplot(111,projection='3d') if X.ndim<2: X = np.tile(np.array(X),(Y.shape[-1],1)).transpose() if Y.ndim<2: Y = np.tile(np.array(Y),(X.shape[0],1)) axes.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=cmap,alpha=alpha,linewidth=linewidth,label=label) axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic') axes.set_xlim(X.min(),X.max()) axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12) axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic') axes.set_ylim(Y.min(),Y.max()) axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12) axes.set_zlabel(zlabel, fontproperties=font, size=10, style='italic') axes.set_zlim(Z.min(),Z.max()) axes.set_zticklabels(axes.get_zticks(),fontproperties=font, size=12)
def _light_colormap(c): r,g,b = colorConverter.to_rgb(c) cdict = {'red': ((0.0, 1.0, 1.0), (1.0, r, r)), 'green': ((0.0, 1.0, 1.0), (1.0, g, g)), 'blue': ((0.0, 1.0, 1.0), (1.0, b, b)) } return LinearSegmentedColormap('_', cdict)
def _dark_colormap(c): r,g,b = colorConverter.to_rgb(c) cdict = {'red': ((0.0, 0.0, 0.0), (1.0, r, r)), 'green': ((0.0, 0.0, 0.0), (1.0, g, g)), 'blue': ((0.0, 0.0, 0.0), (1.0, b, b)) } return LinearSegmentedColormap('_', cdict)
def colorInfoToSegmentDataColorMap(colorInfo): """ make a segmented Data colormap object from a colormap dictionary """ cdict = colorInfo['colors'] keys = list( cdict.keys()) keys = np.sort(keys) color_list = [] for i in range(len(keys)): color_list.append( (keys[i], cdict[keys[i]]) ) colormap = mplColors.LinearSegmentedColormap.from_list(colorInfo['name'], color_list) return colormap
def test_output_type(self): assert isinstance(bwr(), LinearSegmentedColormap)
def test_output_type(self): assert isinstance(seismic(), LinearSegmentedColormap)
def test_output_type(self): assert isinstance(phase(), LinearSegmentedColormap)
def test_output_type(self): assert isinstance(frequency(), LinearSegmentedColormap)
def make_colormap(seq): """Return a LinearSegmentedColormap seq: a sequence of floats and RGB-tuples. The floats should be increasing and in the interval (0,1). """ seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3] cdict = {'red': [], 'green': [], 'blue': []} for i, item in enumerate(seq): if isinstance(item, float): r1, g1, b1 = seq[i - 1] r2, g2, b2 = seq[i + 1] cdict['red'].append([item, r1, r2]) cdict['green'].append([item, g1, g2]) cdict['blue'].append([item, b1, b2]) return mcolors.LinearSegmentedColormap('CustomMap', cdict)
def grey_pal(start=0.2, end=0.8): """ Utility for creating continuous grey scale palette Parameters ---------- start : float grey value at low end of palette end : float grey value at high end of palette Returns ------- out : function Continuous color palette that takes a single :class:`int` parameter ``n`` and returns ``n`` equally spaced colors. >>> palette = grey_pal() >>> palette(5) ['#333333', '#737373', '#989898', '#b5b5b5', '#cccccc'] """ gamma = 2.2 ends = ((0.0, start, start), (1.0, end, end)) cdict = {'red': ends, 'green': ends, 'blue': ends} grey_cmap = mcolors.LinearSegmentedColormap('grey', cdict) def continuous_grey_palette(n): colors = [] # The grey scale points are linearly separated in # gamma encoded space for x in np.linspace(start**gamma, end**gamma, n): # Map points onto the [0, 1] palette domain x = (x ** (1./gamma) - start) / (end - start) colors.append(mcolors.rgb2hex(grey_cmap(x))) return colors return continuous_grey_palette
def plot_probability_of_activation(G, pos, Q): import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap import matplotlib.colors as mcolors def make_colormap(seq): """Return a LinearSegmentedColormap seq: a sequence of floats and RGB-tuples. The floats should be increasing and in the interval (0,1). """ seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3] cdict = {'red': [], 'green': [], 'blue': []} for i, item in enumerate(seq): if isinstance(item, float): r1, g1, b1 = seq[i - 1] r2, g2, b2 = seq[i + 1] cdict['red'].append([item, r1, r2]) cdict['green'].append([item, g1, g2]) cdict['blue'].append([item, b1, b2]) return mcolors.LinearSegmentedColormap('CustomMap', cdict,5000) def get_activation_probability(Q, N): Acti = [0.0]*N for key in Q: acti = [int(u) for u in list(key)] for i,ac in enumerate(acti): Acti[i] += ac*Q[key] return Acti c = mcolors.ColorConverter().to_rgb rvb = make_colormap([c('#d0151d'), c('#f88d59'), 0.2, c('#f88d59') , c('#fbe18f'), 0.4, c('#fbe18f') , c('#e2f3f8'), 0.6,c('#e2f3f8') , c('#96bfdb'), 0.8, c('#96bfdb'), c('#4d74b5')]) node_color = get_activation_probability(Q,len(G.node)) fig = plt.figure(figsize=(7,2.5),frameon=False) edges = nx.draw_networkx_nodes(G,pos=pos,width=6, node_size=1000, linewidths=4,edge_color="#BFBFBF",node_color=node_color,with_labels=False,cmap=rvb) nx.draw_networkx_edges(G,pos=pos,width=4,linewidths=20,edge_color="black") # # plt.xlim([-0.5,0.6]) # plt.ylim([-0.3,0.3]) ax = plt.gca() ax.axis('off') plt.savefig("./test.png") plt.colorbar(edges) plt.savefig("./test_withcolorbar.png") # plt.savefig("./plot/network_activation_3.pdf") # plt.show() return
def plot_probability_of_activation(G, pos, Q): import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap import matplotlib.colors as mcolors def make_colormap(seq): """Return a LinearSegmentedColormap seq: a sequence of floats and RGB-tuples. The floats should be increasing and in the interval (0,1). """ seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3] cdict = {'red': [], 'green': [], 'blue': []} for i, item in enumerate(seq): if isinstance(item, float): r1, g1, b1 = seq[i - 1] r2, g2, b2 = seq[i + 1] cdict['red'].append([item, r1, r2]) cdict['green'].append([item, g1, g2]) cdict['blue'].append([item, b1, b2]) return mcolors.LinearSegmentedColormap('CustomMap', cdict,5000) def get_activation_probability(Q, N): Acti = [0.0]*N for key in Q: acti = [int(u) for u in list(key)] for i,ac in enumerate(acti): Acti[i] += ac*Q[key] return Acti c = mcolors.ColorConverter().to_rgb rvb = make_colormap([c('#4d74b5'),c('#96bfdb'), 0.2, c('#96bfdb') , c('#e2f3f8'), 0.4, c('#e2f3f8') , c('#fbe18f'), 0.6, c('#fbe18f') , c('#f88d59'), 0.8, c('#f88d59'), c('#d0151d')]) node_color = get_activation_probability(Q,len(G.node)) fig = plt.figure(figsize=(5,3),frameon=False) nodes = nx.draw_networkx_nodes(G,pos=pos,width=1, node_size=1200, linewidths=4, edge_color="black",node_color=node_color,with_labels=False,cmap=rvb) nodes.set_edgecolor('black') nx.draw_networkx_edges(G,pos=pos,width=4,edge_color="black") plt.xlim([-0.3,3]) plt.ylim([-0.3,1.2]) ax = plt.gca() ax.axis('off') plt.savefig("./test.png") plt.colorbar(nodes) plt.savefig("./test_withcolorbar.png", bbox_inches='tight', pad_inches=0.1,dpi=200) # plt.savefig("./plot/network_activation_3.pdf") # plt.show() return
def _cmap_discretize(cmap_in, N): """Return a discrete colormap from a continuous colormap. Parameters: cmap_in: `matplotlib.cm <http://matplotlib.org/api/cm_api.html>`_ (colormap) object. N (int): Number of colors. Returns: `matplotlib.cm <http://matplotlib.org/api/cm_api.html>`_ object Example: >>> fig, ax = plt.subplots() >>> im = np.resize(np.arange(100), (5, 100)) >>> dRdBu = _cmap_discretize(cm.RdBu, 5) >>> ax.imshow(im, cmap=dRdBu) """ try: return cmap_in._resample(N) except AttributeError: cdict = cmap_in._segmentdata.copy() # N colors colors_i = np.linspace(0, 1., N) # N+1 indices indices = np.linspace(0, 1., N + 1) for key in ('red', 'green', 'blue'): # Find the N colors D = np.array(cdict[key]) I = interpolate.interp1d(D[:, 0], D[:, 1]) colors = I(colors_i) # Place these colors at the correct indices. A = np.zeros((N + 1, 3), float) A[:, 0] = indices A[1:, 1] = colors A[:-1, 2] = colors # Create a tuple for the dictionary. L = [] for l in A: L.append(tuple(l)) cdict[key] = tuple(L) return LinearSegmentedColormap('colormap', cdict, 1024)
def linearlab(): """Make linearlab color map. `Description of linearlab palatte <https://mycarta.wordpress.com/2012/12/06/the-rainbow-is-deadlong-live-the-rainbow-part-5-cie-lab-linear-l-rainbow/>`_. Returns: cm, cm_r (tuple): `matplotlib.cm <http://matplotlib.org/api/cm_api.html>`_ object and reversed `matplotlib.cm <http://matplotlib.org/api/cm_api.html>`_ object """ linearlab_file = _linearlab_filename() LinL = np.loadtxt(linearlab_file, delimiter=',') b3 = LinL[:, 2] # value of blue at sample n b2 = LinL[:, 2] # value of blue at sample n b1 = np.linspace(0, 1, len(b2)) # position of sample n - ranges from 0 to 1 # setting up columns for list g3 = LinL[:, 1] g2 = LinL[:, 1] g1 = np.linspace(0, 1, len(g2)) r3 = LinL[:, 0] r2 = LinL[:, 0] r1 = np.linspace(0, 1, len(r2)) # creating list R = zip(r1, r2, r3) G = zip(g1, g2, g3) B = zip(b1, b2, b3) # transposing list RGB = zip(R, G, B) rgb = zip(*RGB) # creating dictionary k = ['red', 'green', 'blue'] LinearL = dict(zip(k, rgb)) LinearL_r = _reverse_cmap(LinearL) cmap = LinearSegmentedColormap('linearlab', LinearL) cmap_r = LinearSegmentedColormap('linearlab_r', LinearL_r) return (cmap, cmap_r)
def make_colormap(colors): #------------------------- """ Define a new color map based on values specified in the dictionary colors, where colors[z] is the color that value z should be mapped to, with linear interpolation between the given values of z. The z values (dictionary keys) are real numbers and the values colors[z] can be either an RGB list, e.g. [1,0,0] for red, or an html hex string, e.g. "#ff0000" for red. """ from matplotlib.colors import LinearSegmentedColormap, ColorConverter from numpy import sort z = sort(colors.keys()) n = len(z) z1 = min(z) zn = max(z) x0 = (z - z1) / (zn - z1) CC = ColorConverter() R = [] G = [] B = [] for i in range(n): #i'th color at level z[i]: Ci = colors[z[i]] if type(Ci) == str: # a hex string of form '#ff0000' for example (for red) RGB = CC.to_rgb(Ci) else: # assume it's an RGB triple already: RGB = Ci R.append(RGB[0]) G.append(RGB[1]) B.append(RGB[2]) cmap_dict = {} cmap_dict['red'] = [(x0[i],R[i],R[i]) for i in range(len(R))] cmap_dict['green'] = [(x0[i],G[i],G[i]) for i in range(len(G))] cmap_dict['blue'] = [(x0[i],B[i],B[i]) for i in range(len(B))] mymap = LinearSegmentedColormap('mymap',cmap_dict) return mymap
def cmap_center_point_adjust(cmap, range, center): ''' converts center to a ratio between 0 and 1 of the range given and calls cmap_center_adjust(). returns a new adjusted colormap accordingly NB: nicked from https://sites.google.com/site/theodoregoetz/notes/matplotlib_colormapadjust ''' def cmap_center_adjust(cmap, center_ratio): ''' returns a new colormap based on the one given but adjusted so that the old center point higher (>0.5) or lower (<0.5) ''' if not (0. < center_ratio) & (center_ratio < 1.): return cmap a = math.log(center_ratio) / math.log(0.5) return cmap_powerlaw_adjust(cmap, a) def cmap_powerlaw_adjust(cmap, a): ''' returns a new colormap based on the one given but adjusted via power-law: newcmap = oldcmap**a ''' if a < 0.: return cmap cdict = copy.copy(cmap._segmentdata) fn = lambda x : (x[0]**a, x[1], x[2]) for key in ('red','green','blue'): cdict[key] = map(fn, cdict[key]) cdict[key].sort() assert (cdict[key][0]<0 or cdict[key][-1]>1), \ "Resulting indices extend out of the [0, 1] segment." return colors.LinearSegmentedColormap('colormap',cdict,1024) if not ((range[0] < center) and (center < range[1])): return cmap return cmap_center_adjust(cmap, abs(center - range[0]) / abs(range[1] - range[0]))
def bwr(alpha=0): """ Create a Blue-White-Red colormap given transparency value (alpha, default=0 for seismic cmap) in the middle. :param alpha: Transparency value in the middle between 0 and 1 (default=0). :type alpha: float :return: Blue-White-Red colormap :rtype: matplotlib.colors.LinearSegmentedColormap object """ # Input check if not 0 <= alpha <= 1: raise ValueError("Alpha value must be between 0 and 1.") # Construct cmap dictionary cdict = { 'red': ((0, 0, 0), (0.25, 0, 0), (0.5, 1, 1), (0.75, 0.8314, 0.8314), (1, 0.5, 0.5)), 'green': ((0, 0, 0), (0.25, 0.375, 0.375), (0.5, 1, 1), (0.75, 0.375, 0.375), (1, 0, 0)), 'blue': ((0, 0.5, 0.5), (0.25, 0.8314, 0.8314), (0.5, 1, 1), (0.75, 0, 0), (1, 0, 0)), 'alpha': ((0, 1, 1), (0.5, alpha, alpha), (1, 1, 1)), } return LinearSegmentedColormap('BlueWhiteRed', cdict)
def phase(): """ Create a phase colormap. :return: phase colormap :rtype: matplotlib.colors.LinearSegmentedColormap object """ # Construct cmap dictionary cdict = { 'red': ((0, 1, 1), (0.1, 1, 1), (0.2, 1, 1), (0.3, 1, 1), (0.4, 0.7765, 0.7765), (0.5, 0, 0), (0.6, 0, 0), (0.7, 0, 0), (0.8, 0, 0), (0.9, 0.6314, 0.6314), (1, 1, 1)), 'green': ((0, 0, 0), (0.1, 0, 0), (0.2, 0.4471, 0.4471), (0.3, 0.8941, 0.8941), (0.4, 1, 1), (0.5, 1, 1), (0.6, 1, 1), (0.7, 0.8941, 0.8941), (0.8, 0.4471, 0.4471), (0.9, 0, 0), (1, 0, 0)), 'blue': ((0, 1, 1), (0.1, 0.6314, 0.6314), (0.2, 0, 0), (0.3, 0, 0), (0.4, 0, 0), (0.5, 0, 0), (0.6, 0.7765, 0.7765), (0.7, 1, 1), (0.8, 1, 1), (0.9, 1, 1), (1, 1, 1)), } return LinearSegmentedColormap('Phase', cdict)
def frequency(): """ Create a phase colormap. :return: phase colormap :rtype: matplotlib.colors.LinearSegmentedColormap object """ # Construct cmap dictionary cdict = { 'red': ((0, 0, 0), (0.1, 1, 1), (0.2, 1, 1), (0.3, 0.9412, 0.9412), (0.4, 0.5765, 0.5765), (0.5, 0, 0), (0.6, 0, 0), (0.7, 0, 0), (0.8, 0, 0), (0.9, 0.6667, 0.6667), (1, 1, 1)), 'green': ((0, 0, 0), (0.1, 0, 0), (0.2, 0.7451, 0.7451), (0.3, 1, 1), (0.4, 1, 1), (0.5, 1, 1), (0.6, 1, 1), (0.7, 0.8157, 0.8157), (0.8, 0.3333, 0.3333), (0.9, 0, 0), (1, 0, 0)), 'blue': ((0, 0, 0), (0.1, 0, 0), (0.2, 0, 0), (0.3, 0, 0), (0.4, 0, 0), (0.5, 0.4706, 0.4706), (0.6, 0.8824, 0.8824), (0.7, 1, 1), (0.8, 1, 1), (0.9, 1, 1), (1, 1, 1)), } return LinearSegmentedColormap('Frequency', cdict)
def recentered_cmap(cmap, vmin, vmax): """ Rescale the diverging color map *cmap* such that the center color is at 0 in the data. Returns the rescaled cmap. Based on http://stackoverflow.com/a/20528097 *cmap* is the color map to re-center. Should be a diverging brewer palette. *vmin* is the minimum value in the data being plotted with the *cmap* (must be negative). *vmax* is the maximum value in the data being plotted with the *cmap* (must be positive). """ # regular index to compute the colors reg_index = np.linspace(0.0, 1.0, 257) # shifted index to match the data centerpoint = 1 - vmax/(vmax + abs(vmin)) shift_index = np.hstack([ np.linspace(0.0, centerpoint, 128, endpoint=False), np.linspace(centerpoint, 1.0, 129, endpoint=True) ]) # re-map the colors at each index value using a dictionary cdict = { 'red': [], 'green': [], 'blue': [], 'alpha': [] } for ri, si in zip(reg_index, shift_index): r, g, b, a = cmap(ri) cdict['red'].append((si, r, r)) cdict['green'].append((si, g, g)) cdict['blue'].append((si, b, b)) cdict['alpha'].append((si, a, a)) # save the dictionary as a color map newcmap = LinearSegmentedColormap("recentered", cdict) return newcmap
def shifted_color_map(vmin, vmax, cmap=None): """Shift center of a diverging colormap to value 0 .. note:: This method was found `here <http://stackoverflow.com/questions/ 7404116/defining-the-midpoint-of-a-colormap-in-matplotlib>`_ (last access: 17/01/2017). Thanks to `Paul H <http://stackoverflow.com/ users/1552748/paul-h>`_ who provided it. Function to offset the "center" of a colormap. Useful for data with a negative min and positive max and if you want the middle of the colormap's dynamic range to be at zero level :param vmin: lower end of data value range :param vmax: upper end of data value range :param cmap: colormap (if None, use default cmap: seismic) :return: - shifted colormap """ #midpoint = 1 - abs(im.max())/(abs(im.max()) + abs(im.min())) if cmap is None: cmap = colormaps.seismic midpoint = 1 - abs(vmax)/(abs(vmax) + abs(vmin)) cdict = { 'red': [], 'green': [], 'blue': [], 'alpha': [] } # regular index to compute the colors reg_index = linspace(0, 1, 257) # shifted index to match the data shift_index = hstack([ linspace(0.0, midpoint, 128, endpoint=False), linspace(midpoint, 1.0, 129, endpoint=True) ]) for ri, si in zip(reg_index, shift_index): r, g, b, a = cmap(ri) cdict['red'].append((si, r, r)) cdict['green'].append((si, g, g)) cdict['blue'].append((si, b, b)) cdict['alpha'].append((si, a, a)) #newcmap = colors.LinearSegmentedColormap('shiftedcmap', cdict) #register_cmap(cmap=newcmap) return colors.LinearSegmentedColormap('shiftedcmap', cdict)
def gradient_n_pal(colors, values=None, name='gradientn'): """ Create a n color gradient palette Parameters ---------- colors : list list of colors values : list, optional list of points in the range [0, 1] at which to place each color. Must be the same size as `colors`. Default to evenly space the colors name : str Name to call the resultant MPL colormap Returns ------- out : function Continuous color palette that takes a single parameter either a :class:`float` or a sequence of floats maps those value(s) onto the palette and returns color(s). The float(s) must be in the range [0, 1]. >>> palette = gradient_n_pal(['red', 'blue']) >>> palette([0, .25, .5, .75, 1]) ['#ff0000', '#bf0040', '#7f0080', '#3f00c0', '#0000ff'] """ # Note: For better results across devices and media types, # it would be better to do the interpolation in # Lab color space. if values is None: colormap = mcolors.LinearSegmentedColormap.from_list( name, colors) else: colormap = mcolors.LinearSegmentedColormap.from_list( name, list(zip(values, colors))) def _gradient_n_pal(vals): return ratios_to_colors(vals, colormap) return _gradient_n_pal
def cubehelix_pal(start=0, rot=.4, gamma=1.0, hue=0.8, light=.85, dark=.15, reverse=False): """ Utility for creating continuous palette from the cubehelix system. This produces a colormap with linearly-decreasing (or increasing) brightness. That means that information will be preserved if printed to black and white or viewed by someone who is colorblind. Parameters ---------- start : float, 0 <= start <= 3 The hue at the start of the helix. rot : float Rotations around the hue wheel over the range of the palette. gamma : float 0 <= gamma Gamma factor to emphasize darker (gamma < 1) or lighter (gamma > 1) colors. hue : float, 0 <= hue <= 1 Saturation of the colors. dark : float 0 <= dark <= 1 Intensity of the darkest color in the palette. light : float 0 <= light <= 1 Intensity of the lightest color in the palette. reverse : bool If True, the palette will go from dark to light. Returns ------- out : function Continuous color palette that takes a single :class:`int` parameter ``n`` and returns ``n`` equally spaced colors. References ---------- Green, D. A. (2011). "A colour scheme for the display of astronomical intensity images". Bulletin of the Astromical Society of India, Vol. 39, p. 289-295. >>> palette = cubehelix_pal() >>> palette(5) ['#edd1cb', '#d499a7', '#aa688f', '#6e4071', '#2d1e3e'] """ cdict = mpl._cm.cubehelix(gamma, start, rot, hue) cubehelix_cmap = mpl.colors.LinearSegmentedColormap('cubehelix', cdict) def cubehelix_palette(n): values = np.linspace(light, dark, n) return [mcolors.rgb2hex(cubehelix_cmap(x)) for x in values] return cubehelix_palette