Build histogram of data based on values of color_function
544260
def build_histogram(data, colorscale=None, nbins=10):
    

    if colorscale is None:
        colorscale = colorscale_default

    # TODO: we should weave this method of handling colors into the normal build_histogram and combine both functions
    colorscale = _colors_to_rgb(colorscale)

    h_min, h_max = 0, 1
    hist, bin_edges = np.histogram(data, range=(h_min, h_max), bins=nbins)
    bin_mids = np.mean(np.array(list(zip(bin_edges, bin_edges[1:]))), axis=1)

    histogram = []
    max_bucket_value = max(hist)
    sum_bucket_value = sum(hist)
    for bar, mid in zip(hist, bin_mids):
        height = np.floor(((bar / max_bucket_value) * 100) + 0.5)
        perc = round((bar / sum_bucket_value) * 100.0, 1)
        color = _map_val2color(mid, 0.0, 1.0, colorscale)

        histogram.append({"height": height, "perc": perc, "color": color})

    return histogram
177232
def gdk(self, color):
        """"""
        c = self.parse(color)
        return gdk.Color.from_floats(c)
295836
def plot_log_histogram(df, palette, title, histnorm=""):
    
    data = [go.Histogram(x=np.log10(df.loc[df["dataset"] == d, "lengths"]),
                         opacity=0.4,
                         name=d,
                         histnorm=histnorm,
                         marker=dict(color=c))
            for d, c in zip(df["dataset"].unique(), palette)]
    xtickvals = [10**i for i in range(10) if not 10**i > 10 * np.amax(df["lengths"])]
    html = plotly.offline.plot(
        {"data": data,
         "layout": go.Layout(barmode='overlay',
                             title=title,
                             xaxis=dict(tickvals=np.log10(xtickvals),
                                        ticktext=xtickvals))},
        output_type="div",
        show_link=False)
    fig = go.Figure(
        {"data": data,
         "layout": go.Layout(barmode='overlay',
                             title=title,
                             xaxis=dict(tickvals=np.log10(xtickvals),
                                        ticktext=xtickvals))})
    return html, fig
1263000
def build_colormap(palette, dtype, info):
        """"""
        from trollimage.colormap import Colormap
        sqpalette = np.asanyarray(palette).squeeze() / 255.0
        if hasattr(palette, 'attrs') and 'palette_meanings' in palette.attrs:
            meanings = palette.attrs['palette_meanings']
            iterator = zip(meanings, sqpalette)
        else:
            iterator = enumerate(sqpalette[:-1])

        if dtype == np.dtype('uint8'):
            tups = [(val, tuple(tup))
                    for (val, tup) in iterator]
            colormap = Colormap(*tups)

        elif 'valid_range' in info:
            tups = [(val, tuple(tup))
                    for (val, tup) in iterator]
            colormap = Colormap(*tups)

            sf = info.get('scale_factor', np.array(1))
            colormap.set_range(
                *info['valid_range'] * sf + info.get('add_offset', 0))

        return colormap, sqpalette
1116638
def compute_histogram(values, edges, use_orig_distr=False):
    """"""

    if use_orig_distr:
        return values

    # ignoring invalid values: Inf and Nan
    values = check_array(values).compressed()

    hist, bin_edges = np.histogram(values, bins=edges, density=True)
    hist = preprocess_histogram(hist, values, edges)

    return hist
315882
def chart(colors, data, args, labels):
    """"""
    len_categories = len(data[0])
    if len_categories > 1:
        # Stacked graph
        if args['stacked']:
            normal_dat = normalize(data, args['width'])
            stacked_graph(labels, data, normal_dat, len_categories,
                          args, colors)
            return

        if not colors:
            colors = [None] * len_categories

        # Multiple series graph with different scales
        # Normalization per category
        if args['different_scale']:
            for i in range(len_categories):
                cat_data = []
                for dat in data:
                    cat_data.append([dat[i]])

                # Normalize data, handle negatives.
                normal_cat_data = normalize(cat_data, args['width'])

                # Generate data for a row.
                for row in horiz_rows(labels, cat_data, normal_cat_data,
                                      args, [colors[i]]):
                    # Print the row
                    if not args['vertical']:
                        print_row(*row)
                    else:
                        vertic = vertically(*row, args=args)

                # Vertical graph
                if args['vertical']:
                    print_vertical(vertic, labels, colors[i], args)

                print()
                value_list.clear(), zipped_list.clear(), vertical_list.clear()
                return

    # One category/Multiple series graph with same scale
    # All-together normalization
    if not args['stacked']:
        normal_dat = normalize(data, args['width'])
        for row in horiz_rows(labels, data, normal_dat, args, colors):
            if not args['vertical']:
                print_row(*row)
            else:
                vertic = vertically(*row, args=args)

        if args['vertical'] and len_categories == 1:
            if colors:
                color = colors[0]
            else:
                color = None

            print_vertical(vertic, labels, color, args)

        print()
760669
def plot_data():
    '''

    '''

    var = ['temp', 'oxygen', 'salinity', 'fluorescence-ECO', 'density', 'PAR', 'turbidity', 'fluorescence-CDOM']
    # colorbar limits for each property
    lims = np.array([[26, 33], [0, 10], [0, 36], [0, 6], [1005, 1025], [0, 0.6], [0, 2], [0, 9]])  # reasonable values
    # lims = np.array([[20,36], [26,33], [1.5,5.6], [0,4], [0,9], [0,1.5]]) # values to show colormaps

    for fname in fnames:
        fig, axes = plt.subplots(nrows=4, ncols=2)
        fig.set_size_inches(20, 10)
        fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99, wspace=0.0, hspace=0.07)
        i = 0
        for ax, Var, cmap in zip(axes.flat, var, cmaps):  # loop through data to plot up

            # get variable data
            lat, lon, z, data = test.read(Var, fname)

            map1 = ax.scatter(lat, -z, c=data, cmap=cmap, s=10, linewidths=0., vmin=lims[i, 0], vmax=lims[i, 1])
            # no stupid offset
            y_formatter = mpl.ticker.ScalarFormatter(useOffset=False)
            ax.xaxis.set_major_formatter(y_formatter)
            if i == 6:
                ax.set_xlabel('Latitude [degrees]')
                ax.set_ylabel('Depth [m]')
            else:
                ax.set_xticklabels([])
                ax.set_yticklabels([])
            ax.set_ylim(-z.max(), 0)
            ax.set_xlim(lat.min(), lat.max())
            cb = plt.colorbar(map1, ax=ax, pad=0.02)
            cb.set_label(cmap.name + ' [' + '$' + cmap.units + '$]')
            i += 1

        fig.savefig('figures/' + fname.split('.')[0] + '.png', bbox_inches='tight')
405055
def _populateHistogram(self):
        """"""
        try :
            buildHistogram.populate1DHist(self._data, self.histogram,
                self.minValue, self.maxValue, self.binWidth)
        except:
            if ((self._data.max() - self._data.min()) < self.binWidth):
                raise ValueError("In histogram1d class, the binWidth is "
                                 "greater than the data range of the array "
                                 "object.")
            else:
                raise SystemError("An error processing the array object "
                                  "information occured in the buildHistogram "
                                  "module of histogram1d.")
440090
def _find_colour(particle, start_index, screen_data):
        
        _, fg2, attr2, bg2 = screen_data
        index = start_index
        for i, colours in enumerate(particle.colours):
            if (fg2, attr2, bg2) == colours:
                index = i
                break
        return index
1111788
def from_floats(red, green, blue):
        """"""

        return Color(int(red * Color.MAX_VALUE),
                     int(green * Color.MAX_VALUE),
                     int(blue * Color.MAX_VALUE))
276938
def color_array_by_hue_mix(value, palette):
    
    if int(value, 2) > 0:

        # Convert bits to list and reverse order to avoid issues with
        # differing lengths
        int_list = [int(i) for i in list(value[2:])]
        int_list.reverse()

        # since this is a 1D array, we need the zeroth elements
        # of np.nonzero.
        locs = np.nonzero(int_list)[0]
        # print(locs)
        # print(palette)
        rgb_vals = [palette[i] for i in locs]

        rgb = [0]*len(rgb_vals[0])  # We don't know if it's rgb or rgba
        for val in rgb_vals:
            for index in range(len(val)):
                rgb[index] += val[index]

        for i in range(len(rgb)):
            rgb[i] /= len(locs)

        return tuple(rgb)

    if int(value, 2) == 0:
        return (1, 1, 1) if len(palette[0]) == 3 else (1, 1, 1, 1)

    return -1
679788
def preprocess_histogram(hist, values, edges):
    """"""

    # working with extremely skewed histograms
    if np.count_nonzero(hist) == 0:
        # all of them above upper bound
        if np.all(values >= edges[-1]):
            hist[-1] = 1
        # all of them below lower bound
        elif np.all(values <= edges[0]):
            hist[0] = 1

    return hist
626644
def _random_color(h_range=(0., 1.),
                  s_range=(.5, 1.),
                  v_range=(.5, 1.),
                  ):
    """"""
    h, s, v = uniform(*h_range), uniform(*s_range), uniform(*v_range)
    r, g, b = hsv_to_rgb(np.array([[[h, s, v]]])).flat
    return r, g, b
1340377
function randColor (colorType) {
  if (colorType === 'rgba') {
    let a = []
    for (let i = 0; i < 3; i++) {
      a.push(tools.rnd(0, 255))
    }
    a.push(Math.round(Math.random() * 10) / 10)
    return `rgba(${a[0]},${a[1]},${a[2]},${a[3]})`
  } else {
    return `#${randData('0123456789abcdef', 6)}`
  }
}
859208
def generateDefaultColorRamp(cls, colorRampEnum):
        
        hue = [(255, 0, 255), (231, 0, 255), (208, 0, 255), (185, 0, 255), (162, 0, 255), (139, 0, 255), (115, 0, 255), (92, 0, 255), (69, 0, 255), (46, 0, 255), (23, 0, 255),        # magenta to blue
                   (0, 0, 255), (0, 23, 255), (0, 46, 255), (0, 69, 255), (0, 92, 255), (0, 115, 255), (0, 139, 255), (0, 162, 255), (0, 185, 255), (0, 208, 255), (0, 231, 255),          # blue to cyan
                   (0, 255, 255), (0, 255, 231), (0, 255, 208), (0, 255, 185), (0, 255, 162), (0, 255, 139), (0, 255, 115), (0, 255, 92), (0, 255, 69), (0, 255, 46), (0, 255, 23),        # cyan to green
                   (0, 255, 0), (23, 255, 0), (46, 255, 0), (69, 255, 0), (92, 255, 0), (115, 255, 0), (139, 255, 0), (162, 255, 0), (185, 255, 0), (208, 255, 0), (231, 255, 0),          # green to yellow
                   (255, 255, 0), (255, 243, 0), (255, 231, 0), (255, 220, 0), (255, 208, 0), (255, 197, 0), (255, 185, 0), (255, 174, 0), (255, 162, 0), (255, 151, 0), (255, 139, 0),    # yellow to orange
                   (255, 128, 0), (255, 116, 0), (255, 104, 0), (255, 93, 0), (255, 81, 0), (255, 69, 0), (255, 58, 0), (255, 46, 0), (255, 34, 0), (255, 23, 0), (255, 11, 0),            # orange to red
                   (255, 0, 0)]                                                                                                                                                            # red

        terrain = [(0, 100, 0), (19, 107, 0), (38, 114, 0), (57, 121, 0), (76, 129, 0), (95, 136, 0), (114, 143, 0), (133, 150, 0), (152, 158, 0), (171, 165, 0), (190, 172, 0),                   # dark green to golden rod yellow
                   (210, 180, 0), (210, 167, 5), (210, 155, 10), (210, 142, 15), (210, 130, 20), (210, 117, 25),                                                                                   # golden rod yellow to orange brown
                   (210, 105, 30), (188, 94, 25), (166, 83, 21), (145, 72, 17), (123, 61, 13), (101, 50, 9),                                                                                       # orange brown to dark brown
                   (80, 40, 5), (95, 59, 27), (111, 79, 50), (127, 98, 73), (143, 118, 95), (159, 137, 118),(175, 157, 141), (191, 176, 164), (207, 196, 186), (223, 215, 209), (239, 235, 232),   # dark brown to white
                   (255, 255, 255)]                                                                                                                                                                # white

        aqua = [(150, 255, 255), (136, 240, 250), (122, 226, 245), (109, 212, 240), (95, 198, 235), (81, 184, 230), (68, 170, 225), (54, 156, 220), (40, 142, 215), (27, 128, 210), (13, 114, 205), # aqua to blue
                (0, 100, 200), (0, 94, 195), (0, 89, 191), (0, 83, 187), (0, 78, 182), (0, 72, 178), (0, 67, 174), (0, 61, 170), (0, 56, 165), (0, 50, 161), (0, 45, 157), (0, 40, 153),            # blue to navy blue
                (0, 36, 143), (0, 32, 134), (0, 29, 125), (0, 25, 115), (0, 21, 106), (0, 18, 97), (0, 14, 88), (0, 10, 78), (0, 7, 69), (0, 3, 60), (0, 0, 51)]                                    # navy blue to dark navy blue


        if (colorRampEnum == ColorRampEnum.COLOR_RAMP_HUE):
            return hue

        elif (colorRampEnum == ColorRampEnum.COLOR_RAMP_TERRAIN):
            return terrain

        elif (colorRampEnum == ColorRampEnum.COLOR_RAMP_AQUA):
            return aqua
574529
def hist_from_counts(counts, normalize=False, cumulative=False, to_str=False, sep=',', min_bin=None, max_bin=None):
    
    counters = [dict((i, c)for i, c in enumerate(counts))]

    intkeys_list = [[c for c in counts_dict if (isinstance(c, int) or (isinstance(c, float) and int(c) == c))]
                    for counts_dict in counters]
    min_bin, max_bin = min_bin or 0, max_bin or len(counts) - 1

    histograms = []
    for intkeys, counts in zip(intkeys_list, counters):
        histograms += [OrderedDict()]
        if not intkeys:
            continue
        if normalize:
            N = sum(counts[c] for c in intkeys)
            for c in intkeys:
                counts[c] = float(counts[c]) / N
        if cumulative:
            for i in range(min_bin, max_bin + 1):
                histograms[-1][i] = counts.get(i, 0) + histograms[-1].get(i - 1, 0)
        else:
            for i in range(min_bin, max_bin + 1):
                histograms[-1][i] = counts.get(i, 0)
    if not histograms:
        histograms = [OrderedDict()]

    # fill in the zero counts between the integer bins of the histogram
    aligned_histograms = []

    for i in range(min_bin, max_bin + 1):
        aligned_histograms += [tuple([i] + [hist.get(i, 0) for hist in histograms])]

    if to_str:
        # FIXME: add header row
        return str_from_table(aligned_histograms, sep=sep, max_rows=365 * 2 + 1)

    return aligned_histograms
315701
def rgb(self, color_tuple):
        """"""
        # Check bounds
        self.color = tuple(map(self._apply_float_bounds, color_tuple[:3]))

        # Include alpha if necessary
        if len(color_tuple) > 3:
            self.alpha = self._apply_float_bounds(color_tuple[3])