Python matplotlib.colors() Examples

The following are 30 code examples of matplotlib.colors(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib , or try the search function .
Example #1
Source File: pyplot.py    From Computable with MIT License 7 votes vote down vote up
def set_cmap(cmap):
    """
    Set the default colormap.  Applies to the current image if any.
    See help(colormaps) for more information.

    *cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or
    the name of a registered colormap.

    See :func:`matplotlib.cm.register_cmap` and
    :func:`matplotlib.cm.get_cmap`.
    """
    cmap = cm.get_cmap(cmap)

    rc('image', cmap=cmap.name)
    im = gci()

    if im is not None:
        im.set_cmap(cmap)

    draw_if_interactive() 
Example #2
Source File: labels.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def label_colors(lbls, cmap=None):
    '''
    label_colors(labels) yields a dict object whose keys are the unique values in labels and whose
      values are the (r,g,b,a) colors that should be assigned to each label.
    label_colors(n) is equivalent to label_colors(range(n)).

    Note that this function uses a heuristic and is not guaranteed to be optimal in any way for any
    value of n--but it generally works well enough for most common purposes.
    
    The following optional arguments may be given:
      * cmap (default: None) specifies a colormap to use as a base. If this is None, then a varianct
        of 'hsv' is used.
    '''
    from neuropythy.graphics import label_cmap
    if pimms.is_int(lbls): lbls = np.arange(lbls)
    lbls0 = np.unique(lbls)
    lbls = np.arange(len(lbls0))
    cm = label_cmap(lbls, cmap=cmap)
    mx = float(len(lbls) - 1)
    m = {k:cm(l/mx) for (k,l) in zip(lbls0, lbls)}
    return m 
Example #3
Source File: core.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def varea_colors(*args, **kwargs):
    '''
    varea_colors(obj) yields an array of colors for the visual area map of the given
      property-bearing object (cortex, tesselation, mesh).
    varea_colors(dict) yields an array of the color for the particular vertex property mapping
      that is given as dict.
    varea_colors() yields a functor version of varea_colors that can be called with one of the
      above arguments; note that this is useful precisely because the returned function
      preserves the arguments passed; e.g. varea_colors(weighted=False)(mesh) is equivalent to
      varea_colors(mesh, weighted=False).

    The following options are accepted:
      * weighted (True) specifies whether to use weight as opacity.
      * weight_min (0.2) specifies that below this weight value, the curvature (or null color)
        should be plotted.
      * property (Ellipsis) specifies the specific property that should be used as the
        eccentricity value; if Ellipsis, will attempt to auto-detect this value.
      * weight (Ellipsis) specifies  the specific property that should be used as the weight value.
      * null_color ('curvature') specifies a color that should be used as the background.
    '''
    return retino_colors(vertex_varea_color, *args, **kwargs) 
Example #4
Source File: core.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def sigma_colors(*args, **kwargs):
    '''
    sigma_colors(obj) yields an array of colors for the pRF-radius map of the given
      property-bearing object (cortex, tesselation, mesh).
    sigma_colors(dict) yields an array of the color for the particular vertex property mapping
      that is given as dict.
    sigma_colors() yields a functor version of sigma_colors that can be called with one of the
      above arguments; note that this is useful precisely because the returned function
      preserves the arguments passed; e.g. sigma_colors(weighted=False)(mesh) is equivalent to
      sigma_colors(mesh, weighted=False).

    Note: radius_colors() is an alias for sigma_colors().

    The following options are accepted:
      * weighted (True) specifies whether to use weight as opacity.
      * weight_min (0.2) specifies that below this weight value, the curvature (or null color)
        should be plotted.
      * property (Ellipsis) specifies the specific property that should be used as the
        eccentricity value; if Ellipsis, will attempt to auto-detect this value.
      * weight (Ellipsis) specifies  the specific property that should be used as the weight value.
      * null_color ('curvature') specifies a color that should be used as the background.
    '''
    return retino_colors(vertex_sigma_color, *args, **kwargs) 
Example #5
Source File: core.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def eccen_colors(*args, **kwargs):
    '''
    eccen_colors(obj) yields an array of colors for the eccentricity map of the given
      property-bearing object (cortex, tesselation, mesh).
    eccen_colors(dict) yields an array of the color for the particular vertex property mapping
      that is given as dict.
    eccen_colors() yields a functor version of eccen_colors that can be called with one of the
      above arguments; note that this is useful precisely because the returned function
      preserves the arguments passed; e.g. eccen_colors(weighted=False)(mesh) is equivalent to
      eccen_colors(mesh, weighted=False).

    The following options are accepted:
      * weighted (True) specifies whether to use weight as opacity.
      * weight_min (0.2) specifies that below this weight value, the curvature (or null color)
        should be plotted.
      * property (Ellipsis) specifies the specific property that should be used as the
        eccentricity value; if Ellipsis, will attempt to auto-detect this value.
      * weight (Ellipsis) specifies  the specific property that should be used as the weight value.
      * null_color ('curvature') specifies a color that should be used as the background.
    '''
    return retino_colors(vertex_eccen_color, *args, **kwargs) 
Example #6
Source File: core.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def color_overlap(color1, *args):
    '''
    color_overlap(color1, color2...) yields the rgba value associated with overlaying color2 on top
      of color1 followed by any additional colors (overlaid left to right). This respects alpha
      values when calculating the results.
    Note that colors may be lists of colors, in which case a matrix of RGBA values is yielded.
    '''
    args = list(args)
    args.insert(0, color1)
    rgba = np.asarray([0.5,0.5,0.5,0])
    for c in args:
        c = to_rgba(c)
        a = c[...,3]
        a0 = rgba[...,3]
        if   np.isclose(a0, 0).all(): rgba = np.ones(rgba.shape) * c
        elif np.isclose(a,  0).all(): continue
        else:                         rgba = times(a, c) + times(1-a, rgba)
    return rgba 
Example #7
Source File: pyplot.py    From neural-network-animation with MIT License 6 votes vote down vote up
def eventplot(positions, orientation='horizontal', lineoffsets=1, linelengths=1,
              linewidths=None, colors=None, linestyles='solid', hold=None,
              **kwargs):
    ax = gca()
    # allow callers to override the hold state by passing hold=True|False
    washold = ax.ishold()

    if hold is not None:
        ax.hold(hold)
    try:
        ret = ax.eventplot(positions, orientation=orientation,
                           lineoffsets=lineoffsets, linelengths=linelengths,
                           linewidths=linewidths, colors=colors,
                           linestyles=linestyles, **kwargs)
        draw_if_interactive()
    finally:
        ax.hold(washold)

    return ret

# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example #8
Source File: pyplot.py    From neural-network-animation with MIT License 6 votes vote down vote up
def hlines(y, xmin, xmax, colors='k', linestyles='solid', label='', hold=None,
           **kwargs):
    ax = gca()
    # allow callers to override the hold state by passing hold=True|False
    washold = ax.ishold()

    if hold is not None:
        ax.hold(hold)
    try:
        ret = ax.hlines(y, xmin, xmax, colors=colors, linestyles=linestyles,
                        label=label, **kwargs)
        draw_if_interactive()
    finally:
        ax.hold(washold)

    return ret

# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example #9
Source File: pyplot.py    From neural-network-animation with MIT License 6 votes vote down vote up
def set_cmap(cmap):
    """
    Set the default colormap.  Applies to the current image if any.
    See help(colormaps) for more information.

    *cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or
    the name of a registered colormap.

    See :func:`matplotlib.cm.register_cmap` and
    :func:`matplotlib.cm.get_cmap`.
    """
    cmap = cm.get_cmap(cmap)

    rc('image', cmap=cmap.name)
    im = gci()

    if im is not None:
        im.set_cmap(cmap)

    draw_if_interactive() 
Example #10
Source File: pyplot.py    From neural-network-animation with MIT License 6 votes vote down vote up
def pie(x, explode=None, labels=None, colors=None, autopct=None,
        pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None,
        radius=None, counterclock=True, wedgeprops=None, textprops=None,
        hold=None):
    ax = gca()
    # allow callers to override the hold state by passing hold=True|False
    washold = ax.ishold()

    if hold is not None:
        ax.hold(hold)
    try:
        ret = ax.pie(x, explode=explode, labels=labels, colors=colors,
                     autopct=autopct, pctdistance=pctdistance, shadow=shadow,
                     labeldistance=labeldistance, startangle=startangle,
                     radius=radius, counterclock=counterclock,
                     wedgeprops=wedgeprops, textprops=textprops)
        draw_if_interactive()
    finally:
        ax.hold(washold)

    return ret

# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example #11
Source File: labels.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def cmap(self, data=None):
        '''
        lblidx.cmap() yields a colormap for the given label index object that assumes that the data
          being plotted will be rescaled such that label 0 is 0 and the highest label value in the
          label index is equal to 1.
        lblidx.cmap(data) yields a colormap that will correctly color the labels given in data if
          data is scaled such that its minimum and maximum value are 0 and 1.
        '''
        import matplotlib.colors
        from_list = matplotlib.colors.LinearSegmentedColormap.from_list
        if data is None: return self.colormap
        data = np.asarray(data).flatten()
        (vmin,vmax) = (np.min(data), np.max(data))
        ii  = np.argsort(self.ids)
        ids = np.asarray(self.ids)[ii]
        if vmin == vmax:
            (vmin,vmax,ii) = (vmin-0.5, vmax+0.5, vmin)
            clr = self.color_lookup(ii)
            return from_list('label1', [(0, clr), (1, clr)])
        q   = (ids >= vmin) & (ids <= vmax)
        ids = ids[q]
        clrs = self.color_lookup(ids)
        vals = (ids - vmin) / (vmax - vmin)
        return from_list('label%d' % len(vals), list(zip(vals, clrs))) 
Example #12
Source File: pyplot.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def vlines(x, ymin, ymax, colors='k', linestyles='solid', label='', hold=None,
           **kwargs):
    ax = gca()
    # allow callers to override the hold state by passing hold=True|False
    washold = ax.ishold()

    if hold is not None:
        ax.hold(hold)
    try:
        ret = ax.vlines(x, ymin, ymax, colors=colors, linestyles=linestyles,
                        label=label, **kwargs)
        draw_if_interactive()
    finally:
        ax.hold(washold)

    return ret

# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example #13
Source File: pyplot.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def pie(x, explode=None, labels=None, colors=None, autopct=None,
        pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None,
        radius=None, hold=None):
    ax = gca()
    # allow callers to override the hold state by passing hold=True|False
    washold = ax.ishold()

    if hold is not None:
        ax.hold(hold)
    try:
        ret = ax.pie(x, explode=explode, labels=labels, colors=colors,
                     autopct=autopct, pctdistance=pctdistance, shadow=shadow,
                     labeldistance=labeldistance, startangle=startangle,
                     radius=radius)
        draw_if_interactive()
    finally:
        ax.hold(washold)

    return ret

# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example #14
Source File: pyplot.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def hlines(y, xmin, xmax, colors='k', linestyles='solid', label='', hold=None,
           **kwargs):
    ax = gca()
    # allow callers to override the hold state by passing hold=True|False
    washold = ax.ishold()

    if hold is not None:
        ax.hold(hold)
    try:
        ret = ax.hlines(y, xmin, xmax, colors=colors, linestyles=linestyles,
                        label=label, **kwargs)
        draw_if_interactive()
    finally:
        ax.hold(washold)

    return ret

# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example #15
Source File: tools.py    From python-esppy with Apache License 2.0 6 votes vote down vote up
def getColor(self,name):
        if name.find("#") == 0:
            return(name)

        colors = mcolors.get_named_colors_mapping()

        color = None

        if name in colors:
            color = colors[name]
        elif name == "lightest":
            color = self.lightest
        elif name == "darkest":
            color = self.darkest

        return(color) 
Example #16
Source File: pyplot.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def set_cmap(cmap):
    """
    Set the default colormap.  Applies to the current image if any.
    See help(colormaps) for more information.

    *cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or
    the name of a registered colormap.

    See :func:`matplotlib.cm.register_cmap` and
    :func:`matplotlib.cm.get_cmap`.
    """
    cmap = cm.get_cmap(cmap)

    rc('image', cmap=cmap.name)
    im = gci()

    if im is not None:
        im.set_cmap(cmap)

    draw_if_interactive() 
Example #17
Source File: tools.py    From python-esppy with Apache License 2.0 6 votes vote down vote up
def convertColormap(name):
    cmap = matplotlib.cm.get_cmap(name)
    norm = matplotlib.colors.Normalize(vmin = 0,vmax = 255)
    rgb = []
 
    for i in range(0, 255):
        k = matplotlib.colors.colorConverter.to_rgb(cmap(norm(i)))
        rgb.append(k)

    entries = 255

    h = 1.0 / (entries - 1)
    colorscale = []

    for k in range(entries):
        C = list(map(np.uint8,np.array(cmap(k * h)[:3]) * 255))
        colorscale.append([k * h,"rgb" + str((C[0], C[1], C[2]))])

    return(colorscale) 
Example #18
Source File: pyplot.py    From Computable with MIT License 6 votes vote down vote up
def vlines(x, ymin, ymax, colors='k', linestyles='solid', label='', hold=None,
           **kwargs):
    ax = gca()
    # allow callers to override the hold state by passing hold=True|False
    washold = ax.ishold()

    if hold is not None:
        ax.hold(hold)
    try:
        ret = ax.vlines(x, ymin, ymax, colors=colors, linestyles=linestyles,
                        label=label, **kwargs)
        draw_if_interactive()
    finally:
        ax.hold(washold)

    return ret

# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example #19
Source File: pyplot.py    From Computable with MIT License 6 votes vote down vote up
def pie(x, explode=None, labels=None, colors=None, autopct=None,
        pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None,
        radius=None, hold=None):
    ax = gca()
    # allow callers to override the hold state by passing hold=True|False
    washold = ax.ishold()

    if hold is not None:
        ax.hold(hold)
    try:
        ret = ax.pie(x, explode=explode, labels=labels, colors=colors,
                     autopct=autopct, pctdistance=pctdistance, shadow=shadow,
                     labeldistance=labeldistance, startangle=startangle,
                     radius=radius)
        draw_if_interactive()
    finally:
        ax.hold(washold)

    return ret

# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example #20
Source File: pyplot.py    From Computable with MIT License 6 votes vote down vote up
def hlines(y, xmin, xmax, colors='k', linestyles='solid', label='', hold=None,
           **kwargs):
    ax = gca()
    # allow callers to override the hold state by passing hold=True|False
    washold = ax.ishold()

    if hold is not None:
        ax.hold(hold)
    try:
        ret = ax.hlines(y, xmin, xmax, colors=colors, linestyles=linestyles,
                        label=label, **kwargs)
        draw_if_interactive()
    finally:
        ax.hold(washold)

    return ret

# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example #21
Source File: backend_macosx.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def _read_ppm_image(self, filename):
        data = ""
        imagefile = open(filename)
        for line in imagefile:
            if "#" in line:
                i = line.index("#")
                line = line[:i] + "\n"
            data += line
        imagefile.close()
        magic, width, height, maxcolor, imagedata = data.split(None, 4)
        width, height = int(width), int(height)
        assert magic=="P6"
        assert len(imagedata)==width*height*3 # 3 colors in RGB
        return (width, height, imagedata) 
Example #22
Source File: backend_bases.py    From Computable with MIT License 5 votes vote down vote up
def draw_gouraud_triangles(self, gc, triangles_array, colors_array,
                               transform):
        """
        Draws a series of Gouraud triangles.

        *points* is a Nx3x2 array of (x, y) points for the trianglex.

        *colors* is a Nx3x4 array of RGBA colors for each point of the
        triangles.

        *transform* is an affine transform to apply to the points.
        """
        transform = transform.frozen()
        for tri, col in zip(triangles_array, colors_array):
            self.draw_gouraud_triangle(gc, tri, col, transform) 
Example #23
Source File: backend_bases.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def draw_gouraud_triangle(self, gc, points, colors, transform):
        """
        Draw a Gouraud-shaded triangle.

        *points* is a 3x2 array of (x, y) points for the triangle.

        *colors* is a 3x4 array of RGBA colors for each point of the
        triangle.

        *transform* is an affine transform to apply to the points.
        """
        raise NotImplementedError 
Example #24
Source File: backend_macosx.py    From Computable with MIT License 5 votes vote down vote up
def _read_ppm_image(self, filename):
        data = ""
        imagefile = open(filename)
        for line in imagefile:
            if "#" in line:
                i = line.index("#")
                line = line[:i] + "\n"
            data += line
        imagefile.close()
        magic, width, height, maxcolor, imagedata = data.split(None, 4)
        width, height = int(width), int(height)
        assert magic=="P6"
        assert len(imagedata)==width*height*3 # 3 colors in RGB
        return (width, height, imagedata) 
Example #25
Source File: backend_macosx.py    From Computable with MIT License 5 votes vote down vote up
def draw_gouraud_triangle(self, gc, points, colors, transform):
        points = transform.transform(points)
        gc.draw_gouraud_triangle(points, colors) 
Example #26
Source File: pyplot.py    From Computable with MIT License 5 votes vote down vote up
def get_plot_commands():
    """
    Get a sorted list of all of the plotting commands.
    """
    # This works by searching for all functions in this module and
    # removing a few hard-coded exclusions, as well as all of the
    # colormap-setting functions, and anything marked as private with
    # a preceding underscore.

    import inspect

    exclude = set(['colormaps', 'colors', 'connect', 'disconnect',
                   'get_plot_commands', 'get_current_fig_manager',
                   'ginput', 'plotting', 'waitforbuttonpress'])
    exclude |= set(colormaps())
    this_module = inspect.getmodule(get_plot_commands)

    commands = set()
    for name, obj in globals().items():
        if name.startswith('_') or name in exclude:
            continue
        if inspect.isfunction(obj) and inspect.getmodule(obj) is this_module:
            commands.add(name)

    commands = list(commands)
    commands.sort()
    return commands 
Example #27
Source File: backend_bases.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def draw_gouraud_triangles(self, gc, triangles_array, colors_array,
                               transform):
        """
        Draws a series of Gouraud triangles.

        *points* is a Nx3x2 array of (x, y) points for the trianglex.

        *colors* is a Nx3x4 array of RGBA colors for each point of the
        triangles.

        *transform* is an affine transform to apply to the points.
        """
        transform = transform.frozen()
        for tri, col in zip(triangles_array, colors_array):
            self.draw_gouraud_triangle(gc, tri, col, transform) 
Example #28
Source File: backend_bases.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def set_alpha(self, alpha):
        """
        Set the alpha value used for blending - not supported on all backends.
        If ``alpha=None`` (the default), the alpha components of the
        foreground and fill colors will be used to set their respective
        transparencies (where applicable); otherwise, ``alpha`` will override
        them.
        """
        if alpha is not None:
            self._alpha = alpha
            self._forced_alpha = True
        else:
            self._alpha = 1.0
            self._forced_alpha = False
        self.set_foreground(self._orig_color) 
Example #29
Source File: backend_bases.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def set_foreground(self, fg, isRGBA=False):
        """
        Set the foreground color.  fg can be a MATLAB format string, a
        html hex color string, an rgb or rgba unit tuple, or a float between 0
        and 1.  In the latter case, grayscale is used.

        If you know fg is rgba, set ``isRGBA=True`` for efficiency.
        """
        self._orig_color = fg
        if self._forced_alpha:
            self._rgb = colors.colorConverter.to_rgba(fg, self._alpha)
        elif isRGBA:
            self._rgb = fg
        else:
            self._rgb = colors.colorConverter.to_rgba(fg) 
Example #30
Source File: backend_bases.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def draw_path_collection(self, gc, master_transform, paths, all_transforms,
                             offsets, offsetTrans, facecolors, edgecolors,
                             linewidths, linestyles, antialiaseds, urls,
                             offset_position):
        """
        Draws a collection of paths selecting drawing properties from
        the lists *facecolors*, *edgecolors*, *linewidths*,
        *linestyles* and *antialiaseds*. *offsets* is a list of
        offsets to apply to each of the paths.  The offsets in
        *offsets* are first transformed by *offsetTrans* before being
        applied.  *offset_position* may be either "screen" or "data"
        depending on the space that the offsets are in.

        This provides a fallback implementation of
        :meth:`draw_path_collection` that makes multiple calls to
        :meth:`draw_path`.  Some backends may want to override this in
        order to render each set of path data only once, and then
        reference that path multiple times with the different offsets,
        colors, styles etc.  The generator methods
        :meth:`_iter_collection_raw_paths` and
        :meth:`_iter_collection` are provided to help with (and
        standardize) the implementation across backends.  It is highly
        recommended to use those generators, so that changes to the
        behavior of :meth:`draw_path_collection` can be made globally.
        """
        path_ids = []
        for path, transform in self._iter_collection_raw_paths(
                master_transform, paths, all_transforms):
            path_ids.append((path, transform))

        for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
            gc, master_transform, all_transforms, path_ids, offsets,
            offsetTrans, facecolors, edgecolors, linewidths, linestyles,
                antialiaseds, urls, offset_position):
            path, transform = path_id
            transform = transforms.Affine2D(
                            transform.get_matrix()).translate(xo, yo)
            self.draw_path(gc0, path, transform, rgbFace)