Show a colormap for a chosen input variable var side by side with
    black and white and jet colormaps.

    :param cmap: Colormap instance
    :param var: Variable to plot.
    :param vmin=None: Min plot value.
    :param vmax=None: Max plot value.
979267
def show(cmap, var, vmin=None, vmax=None):
    '''

    '''

    # get variable data
    lat, lon, z, data = read(var)

    fig = plt.figure(figsize=(16, 12))

    # Plot with grayscale
    ax = fig.add_subplot(3, 1, 1)
    map1 = ax.scatter(lon, -z, c=data, cmap='gray', s=10, linewidths=0., vmin=vmin, vmax=vmax)
    plt.colorbar(map1, ax=ax)

    # Plot with jet
    ax = fig.add_subplot(3, 1, 2)
    map1 = ax.scatter(lon, -z, c=data, cmap='jet', s=10, linewidths=0., vmin=vmin, vmax=vmax)
    plt.colorbar(map1, ax=ax)

    # Plot with cmap
    ax = fig.add_subplot(3, 1, 3)
    map1 = ax.scatter(lon, -z, c=data, cmap=cmap, s=10, linewidths=0., vmin=vmin, vmax=vmax)
    ax.set_xlabel('Longitude [degrees]')
    ax.set_ylabel('Depth [m]')
    plt.colorbar(map1, ax=ax)

    plt.suptitle(var)
231952
def mplcmap_to_palette(cmap, ncolors=None, categorical=False):
    
    from matplotlib.colors import Colormap, ListedColormap

    ncolors = ncolors or 256
    if not isinstance(cmap, Colormap):
        import matplotlib.cm as cm
        # Alias bokeh Category cmaps with mpl tab cmaps
        if cmap.startswith('Category'):
            cmap = cmap.replace('Category', 'tab')
        try:
            cmap = cm.get_cmap(cmap)
        except:
            cmap = cm.get_cmap(cmap.lower())
    if isinstance(cmap, ListedColormap):
        if categorical:
            palette = [rgb2hex(cmap.colors[i%cmap.N]) for i in range(ncolors)]
            return palette
        elif cmap.N > ncolors:
            palette = [rgb2hex(c) for c in cmap(np.arange(cmap.N))]
            if len(palette) != ncolors:
                palette = [palette[int(v)] for v in np.linspace(0, len(palette)-1, ncolors)]
            return palette
    return [rgb2hex(c) for c in cmap(np.linspace(0, 1, ncolors))]
1104019
def plot(x, y, z, color=default_color, **kwargs):
    
    fig = gcf()
    _grow_limits(x, y, z)
    defaults = dict(
        visible_lines=True, color_selected=None, size_selected=1, size=1, connected=True, visible_markers=False
    )
    kwargs = dict(defaults, **kwargs)
    s = ipv.Scatter(x=x, y=y, z=z, color=color, **kwargs)
    s.material.visible = False
    fig.scatters = fig.scatters + [s]
    return s
255020
def add_cmap(name, clst):
    """"""
    global cmaps
    assert len(clst) == min_cmap_len, \
        ValueError("color map '%s' length mismatch %d != %d (needed)" % (
            name, len(clst), min_cmap_len))
    cmaps[name] = ColorMap(name, clst)
1188815
def heatmap(self, partition=None, cmap=CM.Blues):
        

        if isinstance(self.dm, DistanceMatrix):
            length = self.dm.values.shape[0]
        else:
            length = self.dm.shape[0]
        datamax = float(np.abs(self.dm).max())
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ticks_at = [0, 0.5 * datamax, datamax]
        if partition:
            sorting = flatten_list(partition.get_membership())
            self.dm = self.dm.reorder(sorting)
        cax = ax.imshow(
            self.dm.values,
            interpolation='nearest',
            origin='lower',
            extent=[0., length, 0., length],
            vmin=0,
            vmax=datamax,
            cmap=cmap,
        )
        cbar = fig.colorbar(cax, ticks=ticks_at, format='%1.2g')
        cbar.set_label('Distance')
        return fig
923292
def process_cmap(cmap, ncolors=None, provider=None, categorical=False):
    
    providers_checked="matplotlib, bokeh, or colorcet" if provider is None else provider

    if isinstance(cmap, Cycle):
        palette = [rgb2hex(c) if isinstance(c, tuple) else c for c in cmap.values]
    elif isinstance(cmap, list):
        palette = cmap
    elif isinstance(cmap, basestring):
        mpl_cmaps = _list_cmaps('matplotlib')
        bk_cmaps = _list_cmaps('bokeh')
        cet_cmaps = _list_cmaps('colorcet')
        if provider=='matplotlib' or (provider is None and (cmap in mpl_cmaps or cmap.lower() in mpl_cmaps)):
            palette = mplcmap_to_palette(cmap, ncolors, categorical)
        elif provider=='bokeh' or (provider is None and (cmap in bk_cmaps or cmap.capitalize() in bk_cmaps)):
            palette = bokeh_palette_to_palette(cmap, ncolors, categorical)
        elif provider=='colorcet' or (provider is None and cmap in cet_cmaps):
            from colorcet import palette
            if cmap.endswith('_r'):
                palette = list(reversed(palette[cmap[:-2]]))
            else:
                palette = palette[cmap]
        else:
            raise ValueError("Supplied cmap %s not found among %s colormaps." %
                             (cmap,providers_checked))
    else:
        try:
            # Try processing as matplotlib colormap
            palette = mplcmap_to_palette(cmap, ncolors)
        except:
            palette = None
    if not isinstance(palette, list):
        raise TypeError("cmap argument %s expects a list, Cycle or valid %s colormap or palette."
                        % (cmap,providers_checked))
    if ncolors and len(palette) != ncolors:
        return [palette[i%len(palette)] for i in range(ncolors)]
    return palette
138084
function( c, num, variance ){
            if( arguments.length < 3 ){
                variance = ColorRange.DEFAULT_VARIANCE;
            }
            if( arguments.length === 1 ){
                num = c;
                c = undefined;
            }
            var list = new ColorList();
            for( var i=0; i<num; i++){
                list.add(this.getColor(c, variance));
            }
            return list;
        }
1288960
def print_colormaps(cmaps, N=256, returnrgb=True, savefiles=False):
    '''

    '''

    rgb = []

    for cmap in cmaps:

        rgbtemp = cmap(np.linspace(0, 1, N))[np.newaxis, :, :3][0]
        if savefiles:
            np.savetxt(cmap.name + '-rgb.txt', rgbtemp)
        rgb.append(rgbtemp)

    if returnrgb:
        return rgb
295332
def hexbin(x, y, color="purple", **kwargs):
    
    if HAS_SEABORN:
        cmap = sns.light_palette(color, as_cmap=True)
    else:
        cmap = "Purples"
    plt.hexbin(x, y, cmap=cmap, **kwargs)
229170
def mpl_color2xcolor(data, matplotlib_color):
    
    # Convert it to RGBA.
    my_col = numpy.array(mpl.colors.ColorConverter().to_rgba(matplotlib_color))

    # If the alpha channel is exactly 0, then the color is really 'none'
    # regardless of the RGB channels.
    if my_col[-1] == 0.0:
        return data, "none", my_col

    xcol = None
    # RGB values (as taken from xcolor.dtx):
    available_colors = {
        # List white first such that for gray values, the combination
        # white!<x>!black is preferred over, e.g., gray!<y>!black. Note that
        # the order of the dictionary is respected from Python 3.6 on.
        "white": numpy.array([1, 1, 1]),
        "lightgray": numpy.array([0.75, 0.75, 0.75]),
        "gray": numpy.array([0.5, 0.5, 0.5]),
        "darkgray": numpy.array([0.25, 0.25, 0.25]),
        "black": numpy.array([0, 0, 0]),
        #
        "red": numpy.array([1, 0, 0]),
        "green": numpy.array([0, 1, 0]),
        "blue": numpy.array([0, 0, 1]),
        "brown": numpy.array([0.75, 0.5, 0.25]),
        "lime": numpy.array([0.75, 1, 0]),
        "orange": numpy.array([1, 0.5, 0]),
        "pink": numpy.array([1, 0.75, 0.75]),
        "purple": numpy.array([0.75, 0, 0.25]),
        "teal": numpy.array([0, 0.5, 0.5]),
        "violet": numpy.array([0.5, 0, 0.5]),
        # The colors cyan, magenta, yellow, and olive are also
        # predefined by xcolor, but their RGB approximation of the
        # native CMYK values is not very good. Don't use them here.
    }

    available_colors.update(data["custom colors"])

    # Check if it exactly matches any of the colors already available.
    # This case is actually treated below (alpha==1), but that loop
    # may pick up combinations with black before finding the exact
    # match. Hence, first check all colors.
    for name, rgb in available_colors.items():
        if all(my_col[:3] == rgb):
            xcol = name
            return data, xcol, my_col

    # Check if my_col is a multiple of a predefined color and 'black'.
    for name, rgb in available_colors.items():
        if name == "black":
            continue

        if rgb[0] != 0.0:
            alpha = my_col[0] / rgb[0]
        elif rgb[1] != 0.0:
            alpha = my_col[1] / rgb[1]
        else:
            assert rgb[2] != 0.0
            alpha = my_col[2] / rgb[2]

        # The cases 0.0 (my_col == black) and 1.0 (my_col == rgb) are
        # already accounted for by checking in available_colors above.
        if all(my_col[:3] == alpha * rgb) and 0.0 < alpha < 1.0:
            xcol = name + ("!{}!black".format(alpha * 100))
            return data, xcol, my_col

    # Lookup failed, add it to the custom list.
    xcol = "color" + str(len(data["custom colors"]))
    data["custom colors"][xcol] = my_col[:3]

    return data, xcol, my_col
736402
function heatmap(config){
            // private variables
            var _ = {
                radius : 40,
                element : {},
                canvas : {},
                acanvas: {},
                ctx : {},
                actx : {},
                legend: null,
                visible : true,
                width : 0,
                height : 0,
                max : false,
                gradient : false,
                opacity: 180,
                premultiplyAlpha: false,
                bounds: {
                    l: 1000,
                    r: 0,
                    t: 1000,
                    b: 0
                },
                debug: false
            };
            // heatmap store containing the datapoints and information about the maximum
            // accessible via instance.store
            this.store = new store(this);

            this.get = function(key){
                return _[key];
            };
            this.set = function(key, value){
                _[key] = value;
            };
            // configure the heatmap when an instance gets created
            this.configure(config);
            // and initialize it
            this.init();
        }
1167952
def init_heatmap(x_vec, y_vec, hist_matrix, fig, colormap='Blues',
                 alpha=1, grid=False, colorbar=True,
                 vmax='auto', vmin='auto', crop=True):
    
    plt.figure(fig.number)
    ax = fig.gca()

    # set vmax and vmin
    vma = np.amax(hist_matrix) if vmax == 'auto' else vmax
    vmi = np.amin(hist_matrix) if vmin == 'auto' else vmin

    # an error check
    if vma <= vmi:
        vma = vmi + 1

    # grid the space for pcolormesh
    x_grid, y_grid = np.meshgrid(x_vec, y_vec)

    hmap = ax.pcolormesh(x_grid, y_grid, np.array(hist_matrix),
               cmap=colormap, alpha=alpha, shading='gouraud',
               vmax=vma, vmin=vmi)

    if colorbar:
        plt.colorbar(hmap)

    if not grid:
        ax.grid(False)

    if crop:
        ax.set_xlim([x_vec[0], x_vec[-1]])
        ax.set_ylim([y_vec[0], y_vec[-1]])
82797
def plot(self, style='heatmap', legend=False, cmap=None, ax=None):
        
        # styles: 2d, colors, otherwise interpret as trace?
        if ax is None:
            import matplotlib.pyplot as plt
            ax = plt.gca()

        if style == 'heatmap':
            ions = self.columns
            ext = (self.index[0], self.index[-1], min(ions), max(ions))
            grid = self.values[:, np.argsort(self.columns)].transpose()
            if isinstance(self.values, scipy.sparse.spmatrix):
                grid = grid.toarray()
            img = ax.imshow(grid, origin='lower', aspect='auto',
                            extent=ext, cmap=cmap)
            if legend:
                ax.figure.colorbar(img)
        elif style == 'colors':
            # TODO: importing gaussian at the top leads to a whole
            # mess of dependency issues => fix somehow?
            from aston.peak.peak_models import gaussian
            from matplotlib.colors import ListedColormap

            wvs = np.genfromtxt(np.array(self.columns).astype(bytes))
            # wvs = self.columns.astype(float)

            # http://www.ppsloan.org/publications/XYZJCGT.pdf
            vis_filt = np.zeros((3, len(wvs)))
            vis_filt[0] = 1.065 * gaussian(wvs, x=595.8, w=33.33) + \
                0.366 * gaussian(wvs, x=446.8, w=19.44)
            vis_filt[1] = 1.014 * gaussian(np.log(wvs), x=np.log(556.3),
                                           w=0.075)
            vis_filt[2] = 1.839 * gaussian(np.log(wvs), x=np.log(449.8),
                                           w=0.051)
            if isinstance(self.values, scipy.sparse.spmatrix):
                xyz = np.dot(self.values.toarray(), vis_filt.T)
            else:
                xyz = np.dot(self.values.copy(), vis_filt.T)

            # http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
            xyz_rgb = [[3.2404542, -1.5371385, -0.4985314],
                       [-0.9692660, 1.8760108, 0.0415560],
                       [0.0556434, -0.2040259, 1.0572252]]
            xyz_rgb = np.array(xyz_rgb)
            rgb = np.dot(xyz_rgb, xyz.T).T

            # normalize
            rgb[rgb < 0] = 0
            rgb /= np.max(rgb)
            rgb = 1 - np.abs(rgb)

            # plot
            cmask = np.meshgrid(np.arange(rgb.shape[0]), 0)[0]
            ax.imshow(cmask, cmap=ListedColormap(rgb), aspect='auto',
                      extent=(self.index[0], self.index[-1], 0, 1))
            ax.yaxis.set_ticks([])
        else:
            if cmap is not None:
                color = cmap(0, 1)
            else:
                color = 'k'
            self.trace().plot(color=color, ax=ax)
119448
def getcolors(spec, n, cmap=None, value=None):
    
    if cmap is not None and spec is not None:
        from matplotlib.colors import LinearSegmentedColormap
        from matplotlib.cm import get_cmap
        if isinstance(cmap, LinearSegmentedColormap):
            return cmap(value)[:, 0:3]
        if isinstance(cmap, str):
            return get_cmap(cmap, n)(value)[:, 0:3]
    if isinstance(spec, str):
        return [getcolor(spec) for i in range(n)]
    elif isinstance(spec, list) and isinstance(spec[0], str):
        return [getcolor(s) for s in spec]
    elif (isinstance(spec, list) or isinstance(spec, ndarray)) and asarray(spec).shape == (3,):
        return [spec for i in range(n)]
    else:
        return spec
711051
def _mpl_cmap2pgf_cmap(cmap, data):
    
    if isinstance(cmap, mpl.colors.LinearSegmentedColormap):
        return _handle_linear_segmented_color_map(cmap, data)

    assert isinstance(
        cmap, mpl.colors.ListedColormap
    ), "Only LinearSegmentedColormap and ListedColormap are supported"
    return _handle_listed_color_map(cmap, data)
1176199
def cmap2pixmap(cmap, steps=50):
    
    import numpy as np

    inds = np.linspace(0, 1, steps)
    n = len(cmap.clst) - 1
    tups = [cmap.clst[int(x * n)] for x in inds]
    rgbas = [QColor(int(r * 255), int(g * 255),
                    int(b * 255), 255).rgba() for r, g, b in tups]
    im = QImage(steps, 1, QImage.Format_Indexed8)
    im.setColorTable(rgbas)
    for i in range(steps):
        im.setPixel(i, 0, i)
    im = im.scaled(128, 32)
    pm = QPixmap.fromImage(im)
    return pm
144937
def format_variable_map(variable_map, join_lines=True):
  """"""
  rows = []
  rows.append(("Key", "Variable", "Shape", "Type", "Collections", "Device"))
  var_to_collections = _get_vars_to_collections(variable_map)

  sort_key = lambda item: (item[0], item[1].name)
  for key, var in sorted(variable_map_items(variable_map), key=sort_key):
    shape = "x".join(str(dim) for dim in var.get_shape().as_list())
    dtype = repr(var.dtype.base_dtype).replace("tf.", "")
    coll = ", ".join(sorted(var_to_collections[var]))
    rows.append((key, var.op.name, shape, dtype, coll, _format_device(var)))
  return _format_table(rows, join_lines)