Plot lightness of colormaps together.
436247
def plot_lightness(saveplot=False):
    '''

    '''

    from colorspacious import cspace_converter

    dc = 1.
    x = np.linspace(0.0, 1.0, 256)
    locs = []  # locations for text labels

    fig = plt.figure(figsize=(16, 5))
    ax = fig.add_subplot(111)
    fig.subplots_adjust(left=0.03, right=0.97)
    ax.set_xlim(-0.1, len(cm.cmap_d)/2. + 0.1)
    ax.set_ylim(0, 100)
    ax.set_xlabel('Lightness for each colormap', fontsize=14)

    for j, cmapname in enumerate(cm.cmapnames):

        if '_r' in cmapname:  # skip reversed versions for plot
            continue

        cmap = cm.cmap_d[cmapname]  # get the colormap instance
        rgb = cmap(x)[np.newaxis, :, :3]
        lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb)
        L = lab[0, :, 0]
        if L[-1] > L[0]:
            ax.scatter(x+j*dc, L, c=x, cmap=cmap, s=200, linewidths=0.)
        else:
            ax.scatter(x+j*dc, L[::-1], c=x[::-1], cmap=cmap, s=200, linewidths=0.)
        locs.append(x[-1]+j*dc)  # store locations for colormap labels

    # Set up labels for colormaps
    ax.xaxis.set_ticks_position('top')
    ticker = mpl.ticker.FixedLocator(locs)
    ax.xaxis.set_major_locator(ticker)
    formatter = mpl.ticker.FixedFormatter([cmapname for cmapname in cm.cmapnames])
    ax.xaxis.set_major_formatter(formatter)
    labels = ax.get_xticklabels()
    for label in labels:
        label.set_rotation(60)

    if saveplot:
        fig.savefig('figures/lightness.png', bbox_inches='tight')
        fig.savefig('figures/lightness.pdf', bbox_inches='tight')

    plt.show()
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])
1247695
def _plot_kmf_single(df,
                     condition_col,
                     survival_col,
                     censor_col,
                     threshold,
                     title,
                     xlabel,
                     ylabel,
                     ax,
                     with_condition_color,
                     no_condition_color,
                     with_condition_label,
                     no_condition_label,
                     color_map,
                     label_map,
                     color_palette,
                     ci_show,
                     print_as_title):
    
    # make color inputs consistent hex format
    if colors.is_color_like(with_condition_color):
        with_condition_color = colors.to_hex(with_condition_color)
    if colors.is_color_like(no_condition_color):
        no_condition_color = colors.to_hex(no_condition_color)
    ## prepare data to be plotted; producing 3 outputs:
    # - `condition`, series containing category labels to be plotted
    # - `label_map` (mapping condition values to plot labels)
    # - `color_map` (mapping condition values to plotted colors)
    if threshold is not None:
        is_median = threshold == "median"
        if is_median:
            threshold = df[condition_col].median()
        label_suffix = float_str(threshold)
        condition = df[condition_col] > threshold
        default_label_no_condition = "%s ≤ %s" % (condition_col, label_suffix)
        if is_median:
            label_suffix += " (median)"
        default_label_with_condition = "%s > %s" % (condition_col, label_suffix)
        with_condition_label = with_condition_label or default_label_with_condition
        no_condition_label = no_condition_label or default_label_no_condition
        if not label_map:
            label_map = {False: no_condition_label,
                         True: with_condition_label}
        if not color_map:
            color_map = {False: no_condition_color,
                         True: with_condition_color}
    elif df[condition_col].dtype == 'O' or df[condition_col].dtype.name == "category":
        condition = df[condition_col].astype("category")
        if not label_map:
            label_map = dict()
            [label_map.update({condition_value: '{} = {}'.format(condition_col,
                                                        condition_value)})
                     for condition_value in condition.unique()]
        if not color_map:
            rgb_values = sb.color_palette(color_palette, len(label_map.keys()))
            hex_values = [colors.to_hex(col) for col in rgb_values]
            color_map = dict(zip(label_map.keys(), hex_values))
    elif df[condition_col].dtype == 'bool':
        condition = df[condition_col]
        default_label_with_condition = "= {}".format(condition_col)
        default_label_no_condition = "¬ {}".format(condition_col)
        with_condition_label = with_condition_label or default_label_with_condition
        no_condition_label = no_condition_label or default_label_no_condition
        if not label_map:
            label_map = {False: no_condition_label,
                         True: with_condition_label}
        if not color_map:
            color_map = {False: no_condition_color,
                         True: with_condition_color}
    else:
        raise ValueError('Don\'t know how to plot data of type\
                         {}'.format(df[condition_col].dtype))

    # produce kmf plot for each category (group) identified above
    kmf = KaplanMeierFitter()
    grp_desc = list()
    grp_survival_data = dict()
    grp_event_data = dict()
    grp_names = list(condition.unique())
    for grp_name, grp_df in df.groupby(condition):
        grp_survival = grp_df[survival_col]
        grp_event = (grp_df[censor_col].astype(bool))
        grp_label = label_map[grp_name]
        grp_color = color_map[grp_name]
        kmf.fit(grp_survival, grp_event, label=grp_label)
        desc_str = "# {}: {}".format(grp_label, len(grp_survival))
        grp_desc.append(desc_str)
        grp_survival_data[grp_name] = grp_survival
        grp_event_data[grp_name] = grp_event
        if ax:
            ax = kmf.plot(ax=ax, show_censors=True, ci_show=ci_show, color=grp_color)
        else:
            ax = kmf.plot(show_censors=True, ci_show=ci_show, color=grp_color)

    ## format the plot
    # Set the y-axis to range 0 to 1
    ax.set_ylim(0, 1)
    y_tick_vals = ax.get_yticks()
    ax.set_yticklabels(["%d" % int(y_tick_val * 100) for y_tick_val in y_tick_vals])
    # plot title
    if title:
        ax.set_title(title)
    elif print_as_title:
        ax.set_title(' | '.join(grp_desc))
    else:
        [print(desc) for desc in grp_desc]
    # axis labels
    if xlabel:
        ax.set_xlabel(xlabel)
    if ylabel:
        ax.set_ylabel(ylabel)
    
    ## summarize analytical version of results
    ## again using same groups as are plotted
    if len(grp_names) == 2:
        # use log-rank test for 2 groups
        results = logrank_test(grp_survival_data[grp_names[0]],
                               grp_survival_data[grp_names[1]],
                               event_observed_A=grp_event_data[grp_names[0]],
                               event_observed_B=grp_event_data[grp_names[1]])
    elif len(grp_names) == 1:
        # no analytical result for 1 or 0 groups
        results = NullSurvivalResults()
    else:
        # cox PH fitter for >2 groups
        cf = CoxPHFitter()
        cox_df = patsy.dmatrix('+'.join([condition_col, survival_col,
                                         censor_col]),
                               df, return_type='dataframe')
        del cox_df['Intercept']
        results = cf.fit(cox_df, survival_col, event_col=censor_col)
        results.print_summary()
    # add metadata to results object so caller can print them
    results.survival_data_series = grp_survival_data
    results.event_data_series = grp_event_data
    results.desc = grp_desc
    return results
1274384
def _violinplot(val, shade, bw, ax, **kwargs_shade):
    """"""
    density, low_b, up_b = _fast_kde(val, bw=bw)
    x = np.linspace(low_b, up_b, len(density))

    x = np.concatenate([x, x[::-1]])
    density = np.concatenate([-density, density[::-1]])

    ax.fill_betweenx(x, density, alpha=shade, lw=0, **kwargs_shade)
517424
function colorBlend(mode, color1, color2) {
    var ab = color1.alpha, cb, // backdrop
        as = color2.alpha, cs, // source
        ar, cr, r = [];        // result

    ar = as + ab * (1 - as);
    for (var i = 0; i < 3; i++) {
        cb = color1.rgb[i] / 255;
        cs = color2.rgb[i] / 255;
        cr = mode(cb, cs);
        if (ar) {
            cr = (as * cs + ab * (cb
                - as * (cb + cs - cr))) / ar;
        }
        r[i] = cr * 255;
    }

    return new(tree.Color)(r, ar);
}
916881
def color_map_data(self) -> typing.Optional[numpy.ndarray]:
        """"""
        if self.display_data_shape is None:  # is there display data?
            return None
        else:
            return self.__color_map_data if self.__color_map_data is not None else ColorMaps.get_color_map_data_by_id("grayscale")
1068598
def color_reducer(c1, c2):
    """"""
    return tuple(v1 + v2 for v1, v2 in itertools.izip(c1, c2))
241254
def _lightness(color, **kwargs):
    
    l = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[1]
    return NumberValue((l * 100, '%'))
813171
def lighten_color(color, amount):
    """"""
    color = [int(col + (255 - col) * amount) for col in hex_to_rgb(color)]
    return rgb_to_hex(color)
1004739
function hsl(hue, saturation, lightness){
  if (1 == arguments.length) {
    utils.assertColor(hue, 'color');
    return hue.hsla;
  } else {
    return hsla(
        hue
      , saturation
      , lightness
      , new nodes.Unit(1));
  }
}
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
608451
def FunctionalGroupColorMapping(maptype='jet', reverse=False):
    """"""

    small_color = '#f76ab4'
    nucleophilic_color = '#ff7f00'
    hydrophobic_color = '#12ab0d'
    aromatic_color = '#84380b'
    acidic_color = '#e41a1c'
    amide_color = '#972aa8'
    basic_color = '#3c58e5'

    mapping_d = {'G':small_color, 'A':small_color,
                 'S':nucleophilic_color, 'T':nucleophilic_color, 'C':nucleophilic_color,
                 'V':hydrophobic_color, 'L':hydrophobic_color, 'I':hydrophobic_color, 'M':hydrophobic_color, 'P':hydrophobic_color,
                 'F':aromatic_color, 'Y':aromatic_color, 'W':aromatic_color,
                 'D':acidic_color, 'E':acidic_color,
                 'H':basic_color, 'K':basic_color, 'R':basic_color,
                 'N':amide_color, 'Q':amide_color,
                 '*':'#000000'}
    return (None, mapping_d, None)
525376
def _hexplot(matrix, fig, colormap):
    
    umatrix_min = matrix.min()
    umatrix_max = matrix.max()
    n_rows, n_columns = matrix.shape
    cmap = plt.get_cmap(colormap)
    offsets = np.zeros((n_columns * n_rows, 2))
    facecolors = []
    for row in range(n_rows):
        for col in range(n_columns):
            if row % 2 == 0:
                offsets[row * n_columns + col] = [col +
                                                  0.5, 2 * n_rows - 2 * row]
                facecolors.append(cmap((matrix[row, col] - umatrix_min) /
                                       (umatrix_max) * 255))
            else:
                offsets[row * n_columns + col] = [col, 2 * n_rows - 2 * row]
                facecolors.append(cmap((matrix[row, col] - umatrix_min) /
                                       (umatrix_max) * 255))
    polygon = np.zeros((6, 2), float)
    polygon[:, 0] = 1.1 * np.array([0.5, 0.5, 0.0, -0.5, -0.5, 0.0])
    polygon[:, 1] = 1.1 * np.array([-np.sqrt(3) / 6, np.sqrt(3) / 6,
                                    np.sqrt(3) / 2 + np.sqrt(3) / 6,
                                    np.sqrt(3) / 6, -np.sqrt(3) / 6,
                                    -np.sqrt(3) / 2 - np.sqrt(3) / 6])
    polygons = np.expand_dims(polygon, 0) + np.expand_dims(offsets, 1)
    ax = fig.gca()
    collection = mcoll.PolyCollection(
        polygons,
        offsets=offsets,
        facecolors=facecolors,
        edgecolors=facecolors,
        linewidths=1.0,
        offset_position="data")
    ax.add_collection(collection, autolim=False)
    corners = ((-0.5, -0.5), (n_columns + 0.5, 2 * n_rows + 0.5))
    ax.update_datalim(corners)
    ax.autoscale_view(tight=True)
    return offsets
554583
def plot(f, lcar=1.0e-1):
    
    import matplotlib
    import matplotlib.pyplot as plt
    import pygmsh

    geom = pygmsh.built_in.Geometry()
    geom.add_circle([0.0, 0.0, 0.0], 1.0, lcar, num_sections=4, compound=True)
    points, cells, _, _, _ = pygmsh.generate_mesh(geom, verbose=True)

    x = points[:, 0]
    y = points[:, 1]
    triang = matplotlib.tri.Triangulation(x, y, cells["triangle"])

    plt.tripcolor(triang, f(points.T), shading="flat")
    plt.colorbar()

    # Choose a diverging colormap such that the zeros are clearly
    # distinguishable.
    plt.set_cmap("coolwarm")
    # Make sure the color map limits are symmetric around 0.
    clim = plt.gci().get_clim()
    mx = max(abs(clim[0]), abs(clim[1]))
    plt.clim(-mx, mx)

    # circle outline
    circle = plt.Circle((0, 0), 1.0, edgecolor="k", fill=False)
    plt.gca().add_artist(circle)

    plt.gca().set_aspect("equal")
    plt.axis("off")
    return
592070
def color_as_heatmap(self, weights, max_weight=1.0, color=DEFAULT_COLORMAP):
        '''
        
        '''
        import numpy as np
        adjusted_weights = np.clip(weights, 0., max_weight) / max_weight
        self.vc = colors_like(adjusted_weights, self.v, colormap=color)
391705
def color_interp(data):
    """"""
    from rasterio.enums import ColorInterp as ci
    modes = {'L': [ci.gray],
             'LA': [ci.gray, ci.alpha],
             'YCbCr': [ci.Y, ci.Cb, ci.Cr],
             'YCbCrA': [ci.Y, ci.Cb, ci.Cr, ci.alpha]}

    try:
        mode = ''.join(data['bands'].values)
        return modes[mode]
    except KeyError:
        colors = {'R': ci.red,
                  'G': ci.green,
                  'B': ci.blue,
                  'A': ci.alpha,
                  'C': ci.cyan,
                  'M': ci.magenta,
                  'Y': ci.yellow,
                  'H': ci.hue,
                  'S': ci.saturation,
                  'L': ci.lightness,
                  'K': ci.black,
                  }
        return [colors[band] for band in data['bands'].values]
252613
def plot_phens_blits(phen_grid, patches, **kwargs):
    

    denom, palette = get_kwargs(phen_grid, kwargs)
    grid = color_grid(phen_grid, palette, denom)

    for i in range(len(grid)):
        for j in range(len(grid[i])):
            curr_patch = patches[i * len(grid[i]) + j]
            if grid[i][j] == -1:
                curr_patch.set_visible(False)
            else:
                curr_patch.set_facecolor(grid[i][j])
                curr_patch.set_visible(True)

    return patches