Add colour scale to heatmap.
2712
def add_mpl_colorscale(fig, heatmap_gs, ax_map, params, title=None):
    """"""
    # Set tick intervals
    cbticks = [params.vmin + e * params.vdiff for e in (0, 0.25, 0.5, 0.75, 1)]
    if params.vmax > 10:
        exponent = int(floor(log10(params.vmax))) - 1
        cbticks = [int(round(e, -exponent)) for e in cbticks]

    scale_subplot = gridspec.GridSpecFromSubplotSpec(
        1, 3, subplot_spec=heatmap_gs[0, 0], wspace=0.0, hspace=0.0
    )
    scale_ax = fig.add_subplot(scale_subplot[0, 1])
    cbar = fig.colorbar(ax_map, scale_ax, ticks=cbticks)
    if title:
        cbar.set_label(title, fontsize=6)
    cbar.ax.yaxis.set_ticks_position("left")
    cbar.ax.yaxis.set_label_position("left")
    cbar.ax.tick_params(labelsize=6)
    cbar.outline.set_linewidth(0)
    return cbar
855254
def updateColormap(self):
        """"""
        if self.imgArgs['lut'] is not None:
            self.img.setLookupTable(self.imgArgs['lut'])
            self.img.setLevels(self.imgArgs['levels'])
2125
function Heatmap() {
    var canvas = zrUtil.createCanvas();
    this.canvas = canvas;

    this.blurSize = 30;
    this.pointSize = 20;

    this.maxOpacity = 1;
    this.minOpacity = 0;

    this._gradientPixels = {};
}
1305843
def plot_colormap_components(cmap):
    """"""
    from ._helpers import set_ax_labels  # recursive import protection

    plt.figure(figsize=[8, 4])
    gs = grd.GridSpec(3, 1, height_ratios=[1, 10, 1], hspace=0.05)
    # colorbar
    ax = plt.subplot(gs[0])
    gradient = np.linspace(0, 1, 256)
    gradient = np.vstack((gradient, gradient))
    ax.imshow(gradient, aspect="auto", cmap=cmap, vmin=0., vmax=1.)
    ax.set_title(cmap.name, fontsize=20)
    ax.set_axis_off()
    # components
    ax = plt.subplot(gs[1])
    x = np.arange(cmap.N)
    colors = cmap(x)
    r = colors[:, 0]
    g = colors[:, 1]
    b = colors[:, 2]
    RGB_weight = [0.299, 0.587, 0.114]
    k = np.sqrt(np.dot(colors[:, :3] ** 2, RGB_weight))
    r.clip(0, 1, out=r)
    g.clip(0, 1, out=g)
    b.clip(0, 1, out=b)
    xi = np.linspace(0, 1, x.size)
    plt.plot(xi, r, "r", linewidth=5, alpha=0.6)
    plt.plot(xi, g, "g", linewidth=5, alpha=0.6)
    plt.plot(xi, b, "b", linewidth=5, alpha=0.6)
    plt.plot(xi, k, "k", linewidth=5, alpha=0.6)
    ax.set_xlim(0, 1)
    ax.set_ylim(-0.1, 1.1)
    set_ax_labels(ax=ax, xlabel=None, xticks=False, ylabel="intensity")
    # grayified colorbar
    cmap = grayify_cmap(cmap)
    ax = plt.subplot(gs[2])
    gradient = np.linspace(0, 1, 256)
    gradient = np.vstack((gradient, gradient))
    ax.imshow(gradient, aspect="auto", cmap=cmap, vmin=0., vmax=1.)
    ax.set_axis_off()
273997
def palettebar(height, length, colormap):
    
    cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))
    cbar = (cbar * (colormap.values.max() + 1 - colormap.values.min())
            + colormap.values.min())

    return colormap.palettize(cbar)
812810
def _map_val2color(val, vmin, vmax, colorscale=None):
    
    colorscale = colorscale or colorscale_default

    if vmin >= vmax:
        raise ValueError("vmin should be < vmax")

    scale = list(map(float, np.array(colorscale)[:, 0]))
    colors = np.array(colorscale)[:, 1]

    colors_01 = (
        np.array(list(map(literal_eval, [color[3:] for color in colors]))) / 255.0
    )

    v = (val - vmin) / float((vmax - vmin))  # val is mapped to v in[0,1]

    idx = 0
    # sequential search for the two   consecutive indices idx, idx+1 such that
    # v belongs to the interval  [scale[idx], scale[idx+1]
    while v > scale[idx + 1]:
        idx += 1
    left_scale_val = scale[idx]
    right_scale_val = scale[idx + 1]
    vv = (v - left_scale_val) / (right_scale_val - left_scale_val)

    # get the triplet of three values in [0,1] that represent the rgb color
    # corresponding to val
    val_color01 = colors_01[idx] + vv * (colors_01[idx + 1] - colors_01[idx])
    val_color_0255 = list(map(np.uint8, 255 * val_color01))

    return "rgb" + str(tuple(val_color_0255))
247815
function buildScales() {
            colorScale = d3Scale.scaleLinear()
                .range([colorSchema[0], colorSchema[colorSchema.length - 1]])
                .domain(d3Array.extent(data, getValue))
                .interpolate(d3Interpolate.interpolateHcl);
        }
405577
def setCustomColorRamp(self, colors=[], interpolatedPoints=10):
        
        self._colorRamp = ColorRampGenerator.generateCustomColorRamp(colors, interpolatedPoints)
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]])
1354731
def scale(self, new_max_value=1):
        
        f = new_max_value / self.max
        return ColorRGB(self.r * f,
                        self.g * f,
                        self.b * f,
                        max_value=new_max_value)
1073051
def calendar_heatmap(data, labels, args):
    """"""
    if args['color']:
        colornum = AVAILABLE_COLORS.get(args['color'][0])
    else:
        colornum = AVAILABLE_COLORS.get('blue')

    dt_dict = {}
    for i in range(len(labels)):
        dt_dict[labels[i]] = data[i][0]

    # get max value
    max_val = float(max(data)[0])

    tick_1 = "░"
    tick_2 = "▒"
    tick_3 = "▓"
    tick_4 = "█"

    if args['custom_tick']:
        tick_1 = tick_2 = tick_3 = tick_4 = args['custom_tick']

    # check if start day set, otherwise use one year ago
    if args['start_dt']:
        start_dt = datetime.strptime(args['start_dt'], '%Y-%m-%d')
    else:
        start = datetime.now()
        start_dt = datetime(year=start.year-1, month=start.month,
                            day=start.day)

    # modify start date to be a Monday, subtract weekday() from day
    start_dt = start_dt - timedelta(start_dt.weekday())

    # TODO: legend doesn't line up properly for all start dates/data
    # top legend for months
    sys.stdout.write("     ")
    for month in range(13):
        month_dt = datetime(year=start_dt.year, month=start_dt.month, day=1) +\
                   timedelta(days=month*31)
        sys.stdout.write(month_dt.strftime("%b") + " ")
        if args['custom_tick']: #assume custom tick is emoji which is one wider
            sys.stdout.write(" ")

    sys.stdout.write('\n')

    for day in range(7):
        sys.stdout.write(DAYS[day] + ': ')
        for week in range(53):
            day_ = start_dt + timedelta(days=day + week*7)
            day_str = day_.strftime("%Y-%m-%d")

            if day_str in dt_dict:
                if dt_dict[day_str] > max_val * 0.75:
                    tick = tick_4
                elif dt_dict[day_str] > max_val * 0.50:
                    tick = tick_3
                elif dt_dict[day_str] > max_val * 0.25:
                    tick = tick_2
                else:
                    tick = tick_1
            else:
                tick = ' '

            if colornum:
                sys.stdout.write(f'\033[{colornum}m')

            sys.stdout.write(tick)
            if colornum:
                sys.stdout.write('\033[0m')

        sys.stdout.write('\n')
1295330
def _add_scale(self, m, ax1):
        '''  '''

        lol, loM, lam, laM = self.lambert_window(
            0.6 * self.size_window, self.lat0, self.lon0)
        m.drawmapscale(loM, lam, self.lon0, self.lat0, 10,
                       barstyle='fancy', units='km',
                       fontsize=24, yoffset=None,
                       labelstyle='simple',
                       fontcolor='k',
                       fillcolor1='w',
                       fillcolor2='k', ax=ax1,
                       format='%d',
                       zorder=2)
1139197
def scale(self, vmin=0., vmax=1.):
        
        return StepColormap(
            self.colors,
            index=[vmin + (vmax-vmin)*(x-self.vmin)*1./(self.vmax-self.vmin) for x in self.index],  # noqa
            vmin=vmin,
            vmax=vmax,
            )
904244
def show_colormap(cls, names=[], N=10, show=True, *args, **kwargs):
        """"""
        names = safe_list(names)
        obj = cls(names, N, *args, **kwargs)
        vbox = obj.layout()
        buttons = QDialogButtonBox(QDialogButtonBox.Close, parent=obj)
        buttons.rejected.connect(obj.close)
        vbox.addWidget(buttons)
        if show:
            obj.show()
        return obj
390687
def timeseries_as_heatmap(X, var_names=None, highlightsX=None, color_map=None):
    
    if highlightsX is None:
        highlightsX = []
    if var_names is None:
        var_names = []
    if len(var_names) == 0:
        var_names = np.arange(X.shape[1])
    if var_names.ndim == 2:
        var_names = var_names[:, 0]

    # transpose X
    X = X.T
    minX = np.min(X)

    # insert space into X
    if False:
        # generate new array with highlightsX
        space = 10  # integer
        Xnew = np.zeros((X.shape[0], X.shape[1] + space*len(highlightsX)))
        hold = 0
        _hold = 0
        space_sum = 0
        for ih, h in enumerate(highlightsX):
            _h = h + space_sum
            Xnew[:, _hold:_h] = X[:, hold:h]
            Xnew[:, _h:_h+space] = minX * np.ones((X.shape[0], space))
            # update variables
            space_sum += space
            _hold = _h + space
            hold = h
        Xnew[:, _hold:] = X[:, hold:]

    fig = pl.figure(figsize=(1.5*4, 2*4))
    im = pl.imshow(np.array(X, dtype=np.float_), aspect='auto',
                   interpolation='nearest', cmap=color_map)
    pl.colorbar(shrink=0.5)
    pl.yticks(range(X.shape[0]), var_names)
    for ih, h in enumerate(highlightsX):
        pl.plot([h, h], [0, X.shape[0]], '--', color='black')
    pl.xlim([0, X.shape[1]-1])
    pl.ylim([0, X.shape[0]-1])
269820
def brighten(color, brightness):
    
    h, s, v = rgb_to_hsv(*map(down_scale, color))
    return tuple(map(up_scale, hsv_to_rgb(h, s, v + down_scale(brightness))))
76643
def heatmap(x, y, step=None, min_pt=None, max_pt=None,
                 colormap='Blues', alpha=1, grid=False,
                 colorbar=True, scale='lin',
                 vmax='auto', vmin='auto', crop=True):
    
    (x_vec, y_vec, hist_matrix) = calc_2d_hist(x, y, step, min_pt, max_pt)

    # simple in this case because it is positive counts
    if scale == 'log':
        for row in hist_matrix:
            for i, el in enumerate(row):
                row[i] = 0 if row[i] == 0 else log10(row[i])

    # plot
    fig = plt.figure()
    init_heatmap(x_vec, y_vec, hist_matrix, fig, colormap=colormap,
                 alpha=alpha, grid=grid, colorbar=colorbar,
                 vmax=vmax, vmin=vmin, crop=crop)

    return fig