Python matplotlib.cm.ScalarMappable() Examples

The following are code examples for showing how to use matplotlib.cm.ScalarMappable(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: dinoSARaws   Author: scottyhq   File: isce2overviews.py    MIT License 6 votes vote down vote up
def make_wrapped_phase_cmap(mapname='plasma', vmin=-50, vmax=50, ncolors=64, wrapRate=6.28):
    ''' each color cycle represents wavelength/2 LOS change '''
    cmap = plt.get_cmap(mapname)
    cNorm = colors.Normalize(vmin=0, vmax=1) #re-wrapping normalization
    scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cmap)
    vals = np.linspace(vmin, vmax, ncolors, endpoint=True)
    vals_wrapped = np.remainder(vals, wrapRate) / wrapRate
    # NOTE: if already converted to cm:
    #vals_wrapped = np.remainder(vals - vals.min(), wavelength/2.0) / (wavelength/2.0)
    outname = 'unwrapped-phase-cog.cpt'
    with open(outname, 'w') as fid:
        for val, wval in zip(vals, vals_wrapped):
            cval = scalarMap.to_rgba(wval)
            fid.write('{0} {1} {2} {3} \n'.format(val, #value
                                                  int(cval[0]*255), #R
                                                  int(cval[1]*255), #G
                                                  int(cval[2]*255))) #B
        fid.write('nv 0 0 0 0 \n') #nodata alpha

    return outname 
Example 2
Project: LaserTOF   Author: kyleuckert   File: contour.py    MIT License 6 votes vote down vote up
def changed(self):
        tcolors = [(tuple(rgba),)
                   for rgba in self.to_rgba(self.cvalues, alpha=self.alpha)]
        self.tcolors = tcolors
        hatches = self.hatches * len(tcolors)
        for color, hatch, collection in zip(tcolors, hatches,
                                            self.collections):
            if self.filled:
                collection.set_facecolor(color)
                # update the collection's hatch (may be None)
                collection.set_hatch(hatch)
            else:
                collection.set_color(color)
        for label, cv in zip(self.labelTexts, self.labelCValues):
            label.set_alpha(self.alpha)
            label.set_color(self.labelMappable.to_rgba(cv))
        # add label colors
        cm.ScalarMappable.changed(self) 
Example 3
Project: LaserTOF   Author: kyleuckert   File: pyplot.py    MIT License 6 votes vote down vote up
def spy(Z, precision=0, marker=None, markersize=None, aspect='equal', **kwargs):
    ax = gca()
    hold = kwargs.pop('hold', None)
    # allow callers to override the hold state by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.spy(Z, precision, marker, markersize, aspect, **kwargs)
    finally:
        ax._hold = washold
    if isinstance(ret, cm.ScalarMappable):
        sci(ret)
    return ret

# just to be safe.  Interactive mode can be turned on without
# calling `plt.ion()` so register it again here.
# This is safe because multiple calls to `install_repl_displayhook`
# are no-ops and the registered function respect `mpl.is_interactive()`
# to determine if they should trigger a draw. 
Example 4
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: contour.py    MIT License 6 votes vote down vote up
def changed(self):
        tcolors = [(tuple(rgba),)
                   for rgba in self.to_rgba(self.cvalues, alpha=self.alpha)]
        self.tcolors = tcolors
        hatches = self.hatches * len(tcolors)
        for color, hatch, collection in zip(tcolors, hatches,
                                            self.collections):
            if self.filled:
                collection.set_facecolor(color)
                # update the collection's hatch (may be None)
                collection.set_hatch(hatch)
            else:
                collection.set_color(color)
        for label, cv in zip(self.labelTexts, self.labelCValues):
            label.set_alpha(self.alpha)
            label.set_color(self.labelMappable.to_rgba(cv))
        # add label colors
        cm.ScalarMappable.changed(self) 
Example 5
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: pyplot.py    MIT License 6 votes vote down vote up
def clim(vmin=None, vmax=None):
    """
    Set the color limits of the current image.

    If either *vmin* or *vmax* is None, the image min/max respectively
    will be used for color scaling.

    If you want to set the clim of multiple images, use
    `~.ScalarMappable.set_clim` on every image, for example::

      for im in gca().get_images():
          im.set_clim(0, 0.5)

    """
    im = gci()
    if im is None:
        raise RuntimeError('You must first define an image, e.g., with imshow')

    im.set_clim(vmin, vmax) 
Example 6
Project: dinosar   Author: scottyhq   File: __init__.py    MIT License 6 votes vote down vote up
def write_cmap(outname, vals, scalarMap):
    """Write external cpt colormap file based on matplotlib colormap.

    Parameters
    ----------
    outname : str
        name of output file (e.g. amplitude-cog.cpt)
    vals : float
        values to be mapped to ncolors
    scalarMap: ScalarMappable
        mapping between array value and colormap value between 0 and 1

    """
    with open(outname, 'w') as fid:
        for val in vals:
            cval = scalarMap.to_rgba(val)
            fid.write('{0} {1} {2} {3} \n'.format(val,  # value
                                                  int(cval[0]*255),  # R
                                                  int(cval[1]*255),  # G
                                                  int(cval[2]*255)))  # B
        fid.write('nv 0 0 0 0 \n')  # nodata alpha transparency 
Example 7
Project: dinosar   Author: scottyhq   File: __init__.py    MIT License 6 votes vote down vote up
def make_coherence_cmap(mapname='inferno', vmin=1e-5, vmax=1, ncolors=64,
                        outname='coherence-cog.cpt'):
    """Write default colormap (coherence-cog.cpt) for isce coherence images.

    Parameters
    ----------
    mapname : str
        matplotlib colormap name
    vmin : float
        data value mapped to lower end of colormap
    vmax : float
        data value mapped to upper end of colormap
    ncolors : int
        number of discrete mapped values between vmin and vmax

    """
    cmap = plt.get_cmap(mapname)
    cNorm = colors.Normalize(vmin=vmin, vmax=vmax)
    scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cmap)
    vals = np.linspace(vmin, vmax, ncolors, endpoint=True)

    write_cmap(outname, vals, scalarMap)

    return outname 
Example 8
Project: ble5-nrf52-mac   Author: tomasero   File: contour.py    MIT License 6 votes vote down vote up
def changed(self):
        tcolors = [(tuple(rgba),)
                   for rgba in self.to_rgba(self.cvalues, alpha=self.alpha)]
        self.tcolors = tcolors
        hatches = self.hatches * len(tcolors)
        for color, hatch, collection in zip(tcolors, hatches,
                                            self.collections):
            if self.filled:
                collection.set_facecolor(color)
                # update the collection's hatch (may be None)
                collection.set_hatch(hatch)
            else:
                collection.set_color(color)
        for label, cv in zip(self.labelTexts, self.labelCValues):
            label.set_alpha(self.alpha)
            label.set_color(self.labelMappable.to_rgba(cv))
        # add label colors
        cm.ScalarMappable.changed(self) 
Example 9
Project: Computable   Author: ktraunmueller   File: image.py    MIT License 6 votes vote down vote up
def __init__(self, fig,
                 cmap=None,
                 norm=None,
                 offsetx=0,
                 offsety=0,
                 origin=None,
                 **kwargs
                 ):

        """
        cmap is a colors.Colormap instance
        norm is a colors.Normalize instance to map luminance to 0-1

        kwargs are an optional list of Artist keyword args
        """
        martist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)
        if origin is None:
            origin = rcParams['image.origin']
        self.origin = origin
        self.figure = fig
        self.ox = offsetx
        self.oy = offsety
        self.update(kwargs)
        self.magnification = 1.0 
Example 10
Project: Computable   Author: ktraunmueller   File: pyplot.py    MIT License 6 votes vote down vote up
def spy(Z, precision=0, marker=None, markersize=None, aspect='equal', 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.spy(Z, precision, marker, markersize, aspect, **kwargs)
        draw_if_interactive()
    finally:
        ax.hold(washold)
    if isinstance(ret, cm.ScalarMappable):
        sci(ret)
    return ret


################# REMAINING CONTENT GENERATED BY boilerplate.py ##############


# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example 11
Project: Computable   Author: ktraunmueller   File: colorbar.py    MIT License 6 votes vote down vote up
def colorbar(mappable, cax=None, ax=None, **kw):
    """
    Create a colorbar for a ScalarMappable instance.

    Documentation for the pylab thin wrapper:
    %(colorbar_doc)s
    """
    import matplotlib.pyplot as plt
    if ax is None:
        ax = plt.gca()
    if cax is None:
        cax, kw = make_axes(ax, **kw)
    cax.hold(True)
    cb = Colorbar(cax, mappable, **kw)

    def on_changed(m):
        cb.set_cmap(m.get_cmap())
        cb.set_clim(m.get_clim())
        cb.update_bruteforce(m)

    cbid = mappable.callbacksSM.connect('changed', on_changed)
    mappable.colorbar = cb
    ax.figure.sca(ax)
    return cb 
Example 12
Project: Computable   Author: ktraunmueller   File: colorbar.py    MIT License 6 votes vote down vote up
def colorbar(mappable, cax=None, ax=None, **kw):
    """
    Create a colorbar for a ScalarMappable instance.

    Documentation for the pylab thin wrapper:
    %(colorbar_doc)s
    """
    import matplotlib.pyplot as plt
    if ax is None:
        ax = plt.gca()
    if cax is None:
        cax, kw = make_axes(ax, **kw)
    cax.hold(True)
    cb = Colorbar(cax, mappable, **kw)

    def on_changed(m):
        cb.set_cmap(m.get_cmap())
        cb.set_clim(m.get_clim())
        cb.update_bruteforce(m)

    cbid = mappable.callbacksSM.connect('changed', on_changed)
    mappable.colorbar = cb
    ax.figure.sca(ax)
    return cb 
Example 13
Project: neural-network-animation   Author: miloharper   File: image.py    MIT License 6 votes vote down vote up
def __init__(self, fig,
                 cmap=None,
                 norm=None,
                 offsetx=0,
                 offsety=0,
                 origin=None,
                 **kwargs
                 ):

        """
        cmap is a colors.Colormap instance
        norm is a colors.Normalize instance to map luminance to 0-1

        kwargs are an optional list of Artist keyword args
        """
        martist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)
        if origin is None:
            origin = rcParams['image.origin']
        self.origin = origin
        self.figure = fig
        self.ox = offsetx
        self.oy = offsety
        self.update(kwargs)
        self.magnification = 1.0 
Example 14
Project: neural-network-animation   Author: miloharper   File: pyplot.py    MIT License 6 votes vote down vote up
def spy(Z, precision=0, marker=None, markersize=None, aspect='equal', 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.spy(Z, precision, marker, markersize, aspect, **kwargs)
        draw_if_interactive()
    finally:
        ax.hold(washold)
    if isinstance(ret, cm.ScalarMappable):
        sci(ret)
    return ret


################# REMAINING CONTENT GENERATED BY boilerplate.py ##############


# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example 15
Project: fenics-topopt   Author: zfergus   File: stress_gui.py    MIT License 5 votes vote down vote up
def __init__(self, nelx, nely, stress_calculator, nu, title=""):
        """Initialize plot and plot the initial design"""
        super(StressGUI, self).__init__(nelx, nely, title)
        self.stress_im = self.ax.imshow(
            np.swapaxes(np.zeros((nelx, nely, 4)), 0, 1),
            norm=colors.Normalize(vmin=0, vmax=1), cmap='jet')
        self.fig.colorbar(self.stress_im)
        self.stress_calculator = stress_calculator
        self.nu = nu
        self.myColorMap = colormaps.ScalarMappable(
            norm=colors.Normalize(vmin=0, vmax=1), cmap=colormaps.jet) 
Example 16
Project: fenics-topopt   Author: zfergus   File: stress_gui.py    MIT License 5 votes vote down vote up
def __init__(self, nelx, nely, stress_calculator, nu, title=""):
        """Initialize plot and plot the initial design"""
        super(StressGUI, self).__init__(nelx, nely, title)
        self.stress_im = self.ax.imshow(
            np.swapaxes(np.zeros((nelx, nely, 4)), 0, 1),
            norm=colors.Normalize(vmin=0, vmax=1), cmap='jet')
        self.fig.colorbar(self.stress_im)
        self.stress_calculator = stress_calculator
        self.nu = nu
        self.myColorMap = colormaps.ScalarMappable(
            norm=colors.Normalize(vmin=0, vmax=1), cmap=colormaps.jet) 
Example 17
Project: nmp_qc   Author: priba   File: Plotter.py    MIT License 5 votes vote down vote up
def plot_graph(self, am, position=None, cls=None, fig_name='graph.png'):

        with warnings.catch_warnings():
            warnings.filterwarnings("ignore")

            g = nx.from_numpy_matrix(am)

            if position is None:
                position=nx.drawing.circular_layout(g)

            fig = plt.figure()

            if cls is None:
                cls='r'
            else:
                # Make a user-defined colormap.
                cm1 = mcol.LinearSegmentedColormap.from_list("MyCmapName", ["r", "b"])

                # Make a normalizer that will map the time values from
                # [start_time,end_time+1] -> [0,1].
                cnorm = mcol.Normalize(vmin=0, vmax=1)

                # Turn these into an object that can be used to map time values to colors and
                # can be passed to plt.colorbar().
                cpick = cm.ScalarMappable(norm=cnorm, cmap=cm1)
                cpick.set_array([])
                cls = cpick.to_rgba(cls)
                plt.colorbar(cpick, ax=fig.add_subplot(111))


            nx.draw(g, pos=position, node_color=cls, ax=fig.add_subplot(111))

            fig.savefig(os.path.join(self.plotdir, fig_name)) 
Example 18
Project: dinoSARaws   Author: scottyhq   File: isce2overviews.py    MIT License 5 votes vote down vote up
def make_amplitude_cmap(mapname='gray', vmin=1, vmax=1e5, ncolors=64):
    cmap = plt.get_cmap(mapname)
    #vmax = get_max()
    # NOTE for strong contrast amp return:
    #cNorm = colors.Normalize(vmin=1e3, vmax=1e4)
    cNorm = colors.LogNorm(vmin=vmin, vmax=vmax)
    scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cmap)
    vals = np.linspace(vmin, vmax, ncolors, endpoint=True)
    outname = 'amplitude-cog.cpt'
    write_cmap(outname, vals, scalarMap)

    return outname 
Example 19
Project: dinoSARaws   Author: scottyhq   File: isce2overviews.py    MIT License 5 votes vote down vote up
def make_coherence_cmap(mapname='inferno', vmin=1e-5, vmax=1, ncolors=64):
    cmap = plt.get_cmap(mapname)
    cNorm = colors.Normalize(vmin=vmin, vmax=vmax)
    scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cmap)
    vals = np.linspace(vmin, vmax, ncolors, endpoint=True)
    outname = 'coherence-cog.cpt'
    write_cmap(outname, vals, scalarMap)

    return outname 
Example 20
Project: LaserTOF   Author: kyleuckert   File: collections.py    MIT License 5 votes vote down vote up
def __init__(self, patches, match_original=False, **kwargs):
        """
        *patches*
            a sequence of Patch objects.  This list may include
            a heterogeneous assortment of different patch types.

        *match_original*
            If True, use the colors and linewidths of the original
            patches.  If False, new colors may be assigned by
            providing the standard collection arguments, facecolor,
            edgecolor, linewidths, norm or cmap.

        If any of *edgecolors*, *facecolors*, *linewidths*,
        *antialiaseds* are None, they default to their
        :data:`matplotlib.rcParams` patch setting, in sequence form.

        The use of :class:`~matplotlib.cm.ScalarMappable` is optional.
        If the :class:`~matplotlib.cm.ScalarMappable` matrix _A is not
        None (i.e., a call to set_array has been made), at draw time a
        call to scalar mappable will be made to set the face colors.
        """

        if match_original:
            def determine_facecolor(patch):
                if patch.get_fill():
                    return patch.get_facecolor()
                return [0, 0, 0, 0]

            kwargs['facecolors'] = [determine_facecolor(p) for p in patches]
            kwargs['edgecolors'] = [p.get_edgecolor() for p in patches]
            kwargs['linewidths'] = [p.get_linewidth() for p in patches]
            kwargs['linestyles'] = [p.get_linestyle() for p in patches]
            kwargs['antialiaseds'] = [p.get_antialiased() for p in patches]

        Collection.__init__(self, **kwargs)

        self.set_paths(patches) 
Example 21
Project: LaserTOF   Author: kyleuckert   File: image.py    MIT License 5 votes vote down vote up
def __init__(self, ax,
                 cmap=None,
                 norm=None,
                 interpolation=None,
                 origin=None,
                 filternorm=1,
                 filterrad=4.0,
                 resample=False,
                 **kwargs
                 ):
        """
        interpolation and cmap default to their rc settings

        cmap is a colors.Colormap instance
        norm is a colors.Normalize instance to map luminance to 0-1

        extent is data axes (left, right, bottom, top) for making image plots
        registered with data plots.  Default is to label the pixel
        centers with the zero-based row and column indices.

        Additional kwargs are matplotlib.artist properties

        """
        martist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)
        self._mouseover = True
        if origin is None:
            origin = rcParams['image.origin']
        self.origin = origin
        self.set_filternorm(filternorm)
        self.set_filterrad(filterrad)
        self.set_interpolation(interpolation)
        self.set_resample(resample)
        self.axes = ax

        self._imcache = None

        self.update(kwargs) 
Example 22
Project: LaserTOF   Author: kyleuckert   File: image.py    MIT License 5 votes vote down vote up
def changed(self):
        """
        Call this whenever the mappable is changed so observers can
        update state
        """
        self._imcache = None
        self._rgbacache = None
        cm.ScalarMappable.changed(self) 
Example 23
Project: LaserTOF   Author: kyleuckert   File: image.py    MIT License 5 votes vote down vote up
def set_array(self, A):
        """
        Retained for backwards compatibility - use set_data instead

        ACCEPTS: numpy array A or PIL Image"""
        # This also needs to be here to override the inherited
        # cm.ScalarMappable.set_array method so it is not invoked
        # by mistake.

        self.set_data(A) 
Example 24
Project: LaserTOF   Author: kyleuckert   File: pyplot.py    MIT License 5 votes vote down vote up
def rcdefaults():
    matplotlib.rcdefaults()
    if matplotlib.is_interactive():
        draw_all()


# The current "image" (ScalarMappable) is retrieved or set
# only via the pyplot interface using the following two
# functions: 
Example 25
Project: LaserTOF   Author: kyleuckert   File: pyplot.py    MIT License 5 votes vote down vote up
def gci():
    """
    Get the current colorable artist.  Specifically, returns the
    current :class:`~matplotlib.cm.ScalarMappable` instance (image or
    patch collection), or *None* if no images or patch collections
    have been defined.  The commands :func:`~matplotlib.pyplot.imshow`
    and :func:`~matplotlib.pyplot.figimage` create
    :class:`~matplotlib.image.Image` instances, and the commands
    :func:`~matplotlib.pyplot.pcolor` and
    :func:`~matplotlib.pyplot.scatter` create
    :class:`~matplotlib.collections.Collection` instances.  The
    current image is an attribute of the current axes, or the nearest
    earlier axes in the current figure that contains an image.
    """
    return gcf()._gci() 
Example 26
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: image.py    MIT License 5 votes vote down vote up
def __init__(self, ax,
                 cmap=None,
                 norm=None,
                 interpolation=None,
                 origin=None,
                 filternorm=True,
                 filterrad=4.0,
                 resample=False,
                 **kwargs
                 ):
        """
        interpolation and cmap default to their rc settings

        cmap is a colors.Colormap instance
        norm is a colors.Normalize instance to map luminance to 0-1

        extent is data axes (left, right, bottom, top) for making image plots
        registered with data plots.  Default is to label the pixel
        centers with the zero-based row and column indices.

        Additional kwargs are matplotlib.artist properties

        """
        martist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)
        self._mouseover = True
        if origin is None:
            origin = rcParams['image.origin']
        self.origin = origin
        self.set_filternorm(filternorm)
        self.set_filterrad(filterrad)
        self.set_interpolation(interpolation)
        self.set_resample(resample)
        self.axes = ax

        self._imcache = None

        self.update(kwargs) 
Example 27
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: image.py    MIT License 5 votes vote down vote up
def changed(self):
        """
        Call this whenever the mappable is changed so observers can
        update state
        """
        self._imcache = None
        self._rgbacache = None
        cm.ScalarMappable.changed(self) 
Example 28
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: image.py    MIT License 5 votes vote down vote up
def set_array(self, A):
        """
        Retained for backwards compatibility - use set_data instead.

        Parameters
        ----------
        A : array-like
        """
        # This also needs to be here to override the inherited
        # cm.ScalarMappable.set_array method so it is not invoked by mistake.
        self.set_data(A) 
Example 29
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: image.py    MIT License 5 votes vote down vote up
def set_data(self, A):
        """Set the image array."""
        cm.ScalarMappable.set_array(self,
                                    cbook.safe_masked_invalid(A, copy=True))
        self.stale = True 
Example 30
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: pyplot.py    MIT License 5 votes vote down vote up
def spy(
        Z, precision=0, marker=None, markersize=None, aspect='equal',
        origin='upper', **kwargs):
    __ret = gca().spy(
        Z, precision=precision, marker=marker, markersize=markersize,
        aspect=aspect, origin=origin, **kwargs)
    if isinstance(__ret, cm.ScalarMappable): sci(__ret)  # noqa
    return __ret


# Autogenerated by boilerplate.py.  Do not edit as changes will be lost. 
Example 31
Project: python-wifi-survey-heatmap   Author: jantman   File: heatmap.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _plot(self, a, key, title, gx, gy, num_x, num_y):
        pp.rcParams['figure.figsize'] = (
            self._image_width / 300, self._image_height / 300
        )
        pp.title(title)
        # Interpolate the data
        rbf = Rbf(
            a['x'], a['y'], a[key], function='linear'
        )
        z = rbf(gx, gy)
        z = z.reshape((num_y, num_x))
        # Render the interpolated data to the plot
        pp.axis('off')
        # begin color mapping
        norm = matplotlib.colors.Normalize(
            vmin=min(a[key]), vmax=max(a[key]), clip=True
        )
        mapper = cm.ScalarMappable(norm=norm, cmap='RdYlBu_r')
        # end color mapping
        image = pp.imshow(
            z,
            extent=(0, self._image_width, self._image_height, 0),
            cmap='RdYlBu_r', alpha=0.5, zorder=100
        )
        pp.colorbar(image)
        pp.imshow(self._layout, interpolation='bicubic', zorder=1, alpha=1)
        # begin plotting points
        for idx in range(0, len(a['x'])):
            pp.plot(
                a['x'][idx], a['y'][idx],
                marker='o', markeredgecolor='black', markeredgewidth=1,
                markerfacecolor=mapper.to_rgba(a[key][idx]), markersize=6
            )
        # end plotting points
        fname = '%s_%s.png' % (key, self._title)
        logger.info('Writing plot to: %s', fname)
        pp.savefig(fname, dpi=300)
        pp.close('all') 
Example 32
Project: LSDMappingTools   Author: LSDtopotools   File: colours.py    MIT License 5 votes vote down vote up
def colorbar_index(fig, cax, ncolors, cmap, drape_min_threshold, drape_max):
    """State-machine like function that creates a discrete colormap and plots
       it on a figure that is passed as an argument.

    Arguments:
       fig (matplotlib.Figure): Instance of a matplotlib figure object.
       cax (matplotlib.Axes): Axes instance to create the colourbar from.
           This must be the Axes containing the data that your colourbar will be
           mapped from.
       ncolors (int): The number of colours in the discrete colourbar map.
       cmap (str or Colormap object): Either the name of a matplotlib colormap, or
           an object instance of the colormap, e.g. cm.jet
       drape_min_threshold (float): Number setting the threshold level of the drape raster
           This should match any threshold you have set to mask the drape/overlay raster.
       drape_max (float): Similar to above, but for the upper threshold of your drape mask.
    """

    discrete_cmap = discrete_colourmap(ncolors, cmap)

    mappable = _cm.ScalarMappable(cmap=discrete_cmap)
    mappable.set_array([])
    #mappable.set_clim(-0.5, ncolors + 0.5)
    mappable.set_clim(drape_min_threshold, drape_max)

    print(type(fig))
    print(type(mappable))
    print(type(cax))
    print()
    cbar = _plt.colorbar(mappable, cax=cax) #switched from fig to plt to expose the labeling params
    print(type(cbar))
    #cbar.set_ticks(_np.linspace(0, ncolors, ncolors))
    pad = ((ncolors - 1) / ncolors) / 2  # Move labels to center of bars.
    cbar.set_ticks(_np.linspace(drape_min_threshold + pad, drape_max - pad,
                   ncolors))

    return cbar

# Generate random colormap 
Example 33
Project: dinosar   Author: scottyhq   File: __init__.py    MIT License 5 votes vote down vote up
def make_amplitude_cmap(mapname='gray', vmin=1, vmax=1e5, ncolors=64,
                        outname='amplitude-cog.cpt'):
    """Write default colormap (amplitude-cog.cpt) for isce amplitude images.

    Uses a LogNorm colormap by default since amplitude return values typically
    span several orders of magnitude.

    Parameters
    ----------
    mapname : str
        matplotlib colormap name
    vmin : float
        data value mapped to lower end of colormap
    vmax : float
        data value mapped to upper end of colormap
    ncolors : int
        number of discrete mapped values between vmin and vmax

    """
    cmap = plt.get_cmap(mapname)
    # NOTE for strong contrast amp return:
    # cNorm = colors.Normalize(vmin=1e3, vmax=1e4)
    cNorm = colors.LogNorm(vmin=vmin, vmax=vmax)
    scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cmap)
    vals = np.linspace(vmin, vmax, ncolors, endpoint=True)
    write_cmap(outname, vals, scalarMap)

    return outname 
Example 34
Project: dinosar   Author: scottyhq   File: __init__.py    MIT License 5 votes vote down vote up
def make_wrapped_phase_cmap(mapname='plasma', vmin=-50, vmax=50, ncolors=64,
                            wrapRate=6.28, outname='unwrapped-phase-cog.cpt'):
    """Re-wrap unwrapped phase values and write 'unwrapped-phase-cog.cpt'.

    Each color cycle represents wavelength/2 line-of-sight change for
    wrapRate=6.28.

    Parameters
    ----------
    mapname : str
        matplotlib colormap name
    vmin : float
        data value mapped to lower end of colormap
    vmax : float
        data value mapped to upper end of colormap
    ncolors : int
        number of discrete mapped values between vmin and vmax
    wrapRate : float
        number of radians per phase cycle

    """
    cmap = plt.get_cmap(mapname)
    cNorm = colors.Normalize(vmin=0, vmax=1)  # re-wrapping normalization
    scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cmap)
    vals = np.linspace(vmin, vmax, ncolors, endpoint=True)
    vals_wrapped = np.remainder(vals, wrapRate) / wrapRate

    with open(outname, 'w') as fid:
        for val, wval in zip(vals, vals_wrapped):
            cval = scalarMap.to_rgba(wval)
            fid.write('{0} {1} {2} {3} \n'.format(val,  # value
                                                  int(cval[0]*255),  # R
                                                  int(cval[1]*255),  # G
                                                  int(cval[2]*255)))  # B
        fid.write('nv 0 0 0 0 \n')  # nodata alpha

    return outname 
Example 35
Project: RVO_Py_MAS   Author: MengGuo   File: vis.py    GNU General Public License v2.0 5 votes vote down vote up
def get_cmap(N):
    '''Returns a function that maps each index in 0, 1, ... N-1 to a distinct RGB color.'''
    color_norm  = colors.Normalize(vmin=0, vmax=N-1)
    scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv') 
    def map_index_to_rgb_color(index):
        return scalar_map.to_rgba(index)
    return map_index_to_rgb_color 
Example 36
Project: nmsat   Author: rcfduarte   File: visualization.py    GNU General Public License v2.0 5 votes vote down vote up
def get_cmap(N, cmap='hsv'):
    """
    Returns a function that maps each index in 0, 1, ... N-1 to a distinct
    RGB color.
    """
    color_norm = colors.Normalize(vmin=0, vmax = N-1)
    scalar_map = cmx.ScalarMappable(norm=color_norm, cmap=cmap)

    def map_index_to_rgb_color(index):
        return scalar_map.to_rgba(index)

    return map_index_to_rgb_color 
Example 37
Project: ezaero   Author: partmor   File: plotting.py    MIT License 5 votes vote down vote up
def plot_cl_distribution_on_wing(wing_panels, res, cmap=cm.coolwarm, elev=25,
                                 azim=-160):
    m, n = wing_panels.shape[:2]
    bp = wing_panels[:, :, :, 1].max() - wing_panels[:, :, :, 1].min()
    cl_dist = res.cl

    X, Y, Z = [wing_panels[:, :, :, i] for i in range(3)]
    norm = plt.Normalize()
    face_colors = cmap(norm(cl_dist))
    fig = plt.figure()
    ax = a3.Axes3D(fig)
    for i in range(m):
        for j in range(n):
            vtx = np.array([X[i, j], Y[i, j], Z[i, j]]).T
            panel = a3.art3d.Poly3DCollection([vtx])
            panel.set_facecolor((face_colors[i, j][0], face_colors[
                                i, j][1], face_colors[i, j][2]))
            panel.set_edgecolor('k')
            ax.add_collection3d(panel)
    limits = (-bp / 1.8, bp / 1.8)
    ax.set_xlim(limits)
    ax.set_ylim(limits)
    ax.set_zlim(limits)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    ax.view_init(elev=elev, azim=azim)
    sm = cm.ScalarMappable(norm, cmap)
    sm.set_array(cl_dist)
    cbar = fig.colorbar(sm, shrink=0.5, aspect=6, extend='both')
    cbar.ax.set_xlabel(r'C$_{L_{wing}}$') 
Example 38
Project: gmm_tutorial   Author: sitzikbs   File: visualization.py    MIT License 5 votes vote down vote up
def plot_sphere(w=0, c=[0,0,0], r=[1, 1, 1], subdev=10, ax=None, sigma_multiplier=3):
    '''
        plot a sphere surface
        Input: 
            c: 3 elements list, sphere center
            r: 3 element list, sphere original scale in each axis ( allowing to draw elipsoids)
            subdiv: scalar, number of subdivisions (subdivision^2 points sampled on the surface)
            ax: optional pyplot axis object to plot the sphere in.
            sigma_multiplier: sphere additional scale (choosing an std value when plotting gaussians)
        Output:
            ax: pyplot axis object
    '''

    if ax is None:
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
    pi = np.pi
    cos = np.cos
    sin = np.sin
    phi, theta = np.mgrid[0.0:pi:complex(0,subdev), 0.0:2.0 * pi:complex(0,subdev)]
    x = sigma_multiplier*r[0] * sin(phi) * cos(theta) + c[0]
    y = sigma_multiplier*r[1] * sin(phi) * sin(theta) + c[1]
    z = sigma_multiplier*r[2] * cos(phi) + c[2]
    cmap = cmx.ScalarMappable()
    cmap.set_cmap('jet')
    c = cmap.to_rgba(w)

    ax.plot_surface(x, y, z, color=c, alpha=0.2, linewidth=1)

    return ax 
Example 39
Project: ble5-nrf52-mac   Author: tomasero   File: image.py    MIT License 5 votes vote down vote up
def __init__(self, ax,
                 cmap=None,
                 norm=None,
                 interpolation=None,
                 origin=None,
                 filternorm=True,
                 filterrad=4.0,
                 resample=False,
                 **kwargs
                 ):
        """
        interpolation and cmap default to their rc settings

        cmap is a colors.Colormap instance
        norm is a colors.Normalize instance to map luminance to 0-1

        extent is data axes (left, right, bottom, top) for making image plots
        registered with data plots.  Default is to label the pixel
        centers with the zero-based row and column indices.

        Additional kwargs are matplotlib.artist properties

        """
        martist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)
        self._mouseover = True
        if origin is None:
            origin = rcParams['image.origin']
        self.origin = origin
        self.set_filternorm(filternorm)
        self.set_filterrad(filterrad)
        self.set_interpolation(interpolation)
        self.set_resample(resample)
        self.axes = ax

        self._imcache = None

        self.update(kwargs) 
Example 40
Project: ble5-nrf52-mac   Author: tomasero   File: image.py    MIT License 5 votes vote down vote up
def changed(self):
        """
        Call this whenever the mappable is changed so observers can
        update state
        """
        self._imcache = None
        self._rgbacache = None
        cm.ScalarMappable.changed(self) 
Example 41
Project: ble5-nrf52-mac   Author: tomasero   File: image.py    MIT License 5 votes vote down vote up
def set_array(self, A):
        """
        Retained for backwards compatibility - use set_data instead.

        Parameters
        ----------
        A : array-like
        """
        # This also needs to be here to override the inherited
        # cm.ScalarMappable.set_array method so it is not invoked by mistake.

        self.set_data(A) 
Example 42
Project: ble5-nrf52-mac   Author: tomasero   File: image.py    MIT License 5 votes vote down vote up
def set_data(self, A):
        """Set the image array."""
        cm.ScalarMappable.set_array(self,
                                    cbook.safe_masked_invalid(A, copy=True))
        self.stale = True 
Example 43
Project: ble5-nrf52-mac   Author: tomasero   File: pyplot.py    MIT License 5 votes vote down vote up
def spy(
        Z, precision=0, marker=None, markersize=None, aspect='equal',
        origin='upper', **kwargs):
    __ret = gca().spy(
        Z, precision=precision, marker=marker, markersize=markersize,
        aspect=aspect, origin=origin, **kwargs)
    if isinstance(__ret, cm.ScalarMappable): sci(__ret)  # noqa
    return __ret


# Autogenerated by boilerplate.py.  Do not edit as changes will be lost. 
Example 44
Project: ML-Recipes   Author: rougier   File: pca.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_cmap(N):
    '''Returns a function that maps each index in 0, 1, ... N-1 to a distinct
        RGB color.'''
    color_norm  = colors.Normalize(vmin=0, vmax=N)
    scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv')
    def map_index_to_rgb_color(index):
        return scalar_map.to_rgba(index)
    return map_index_to_rgb_color 
Example 45
Project: mapper   Author: timothy-mcroy   File: MapperGUI.py    GNU General Public License v2.0 5 votes vote down vote up
def Colormap(Filter):
        # tbd: simplify
        import matplotlib.cm as mcm
        cmap = mcm.get_cmap()
        norm = mcm.colors.Normalize(vmin=Filter.min(), vmax=Filter.max())
        return mcm.ScalarMappable(norm=norm, cmap=cmap).to_rgba(Filter) 
Example 46
Project: Computable   Author: ktraunmueller   File: image.py    MIT License 5 votes vote down vote up
def changed(self):
        """
        Call this whenever the mappable is changed so observers can
        update state
        """
        self._imcache = None
        self._rgbacache = None
        cm.ScalarMappable.changed(self) 
Example 47
Project: Computable   Author: ktraunmueller   File: image.py    MIT License 5 votes vote down vote up
def set_array(self, A):
        """
        Retained for backwards compatibility - use set_data instead

        ACCEPTS: numpy array A or PIL Image"""
        # This also needs to be here to override the inherited
        # cm.ScalarMappable.set_array method so it is not invoked
        # by mistake.

        self.set_data(A) 
Example 48
Project: Computable   Author: ktraunmueller   File: image.py    MIT License 5 votes vote down vote up
def set_cmap(self, cmap):
        if self._A is not None:
            raise RuntimeError('Cannot change colors after loading data')
        cm.ScalarMappable.set_cmap(self, cmap) 
Example 49
Project: Computable   Author: ktraunmueller   File: image.py    MIT License 5 votes vote down vote up
def __init__(self, ax,
                 x=None,
                 y=None,
                 A=None,
                 cmap=None,
                 norm=None,
                 **kwargs
                 ):
        """
        cmap defaults to its rc setting

        cmap is a colors.Colormap instance
        norm is a colors.Normalize instance to map luminance to 0-1

        Additional kwargs are matplotlib.artist properties

        """
        martist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)
        self.axes = ax
        self._rgbacache = None
        # There is little point in caching the image itself because
        # it needs to be remade if the bbox or viewlim change,
        # so caching does help with zoom/pan/resize.
        self.update(kwargs)
        self.set_data(x, y, A) 
Example 50
Project: Computable   Author: ktraunmueller   File: image.py    MIT License 5 votes vote down vote up
def changed(self):
        self._rgbacache = None
        cm.ScalarMappable.changed(self) 
Example 51
Project: Computable   Author: ktraunmueller   File: image.py    MIT License 5 votes vote down vote up
def set_data(self, A):
        """Set the image array."""
        cm.ScalarMappable.set_array(self, cbook.safe_masked_invalid(A)) 
Example 52
Project: Computable   Author: ktraunmueller   File: pyplot.py    MIT License 5 votes vote down vote up
def rcdefaults():
    matplotlib.rcdefaults()
    draw_if_interactive()


# The current "image" (ScalarMappable) is retrieved or set
# only via the pyplot interface using the following two
# functions: 
Example 53
Project: Computable   Author: ktraunmueller   File: pyplot.py    MIT License 5 votes vote down vote up
def gci():
    """
    Get the current colorable artist.  Specifically, returns the
    current :class:`~matplotlib.cm.ScalarMappable` instance (image or
    patch collection), or *None* if no images or patch collections
    have been defined.  The commands :func:`~matplotlib.pyplot.imshow`
    and :func:`~matplotlib.pyplot.figimage` create
    :class:`~matplotlib.image.Image` instances, and the commands
    :func:`~matplotlib.pyplot.pcolor` and
    :func:`~matplotlib.pyplot.scatter` create
    :class:`~matplotlib.collections.Collection` instances.  The
    current image is an attribute of the current axes, or the nearest
    earlier axes in the current figure that contains an image.
    """
    return gcf()._gci() 
Example 54
Project: pyrsgis   Author: PratyushTripathy   File: __init__.py    MIT License 5 votes vote down vote up
def display(band, maptitle = 'Pyrsgis Raster', cmap='PRGn'):
    plt.title(maptitle, fontsize=20)
    legend = cm.ScalarMappable(cmap=cmap)
    legend.set_array(np.array([band.min(), band.min()+band.max()/2, band.max()]))
    plt.colorbar(legend)
    plt.imshow(band, cmap=cmap)
    scalebar = ScaleBar(30)
    plt.gca().add_artist(scalebar)
    plt.show() 
Example 55
Project: pyrsgis   Author: PratyushTripathy   File: __init__.py    MIT License 5 votes vote down vote up
def display(band, maptitle = 'Pyrsgis Raster', cmap='PRGn'):
    plt.title(maptitle, fontsize=20)
    legend = cm.ScalarMappable(cmap=cmap)
    legend.set_array(np.array([band.min(), band.min()+band.max()/2, band.max()]))
    plt.colorbar(legend)
    plt.imshow(band, cmap=cmap)
    scalebar = ScaleBar(30)
    plt.gca().add_artist(scalebar)
    plt.show() 
Example 56
Project: GProject   Author: fnbellomo   File: toy_funcs.py    GNU General Public License v2.0 5 votes vote down vote up
def print_func(bodies_list,first):
	ind=0
	for body in bodies_list:
		name	= body.obj_id
		coord	= body.obj_position
		x,y	= coord[0],coord[1]
		plt.plot(x,y,'o',color=cmx.ScalarMappable(norm=colors.Normalize(vmin=0, vmax=len(bodies_list)),cmap=plt.get_cmap('jet')).to_rgba(ind),ms=2,label=name)
		ind	+=1
	if first == True: plt.legend()
	plt.ion()
	plt.draw() 
Example 57
Project: neural-network-animation   Author: miloharper   File: image.py    MIT License 5 votes vote down vote up
def changed(self):
        """
        Call this whenever the mappable is changed so observers can
        update state
        """
        self._imcache = None
        self._rgbacache = None
        cm.ScalarMappable.changed(self) 
Example 58
Project: neural-network-animation   Author: miloharper   File: image.py    MIT License 5 votes vote down vote up
def set_array(self, A):
        """
        Retained for backwards compatibility - use set_data instead

        ACCEPTS: numpy array A or PIL Image"""
        # This also needs to be here to override the inherited
        # cm.ScalarMappable.set_array method so it is not invoked
        # by mistake.

        self.set_data(A) 
Example 59
Project: neural-network-animation   Author: miloharper   File: image.py    MIT License 5 votes vote down vote up
def set_cmap(self, cmap):
        if self._A is not None:
            raise RuntimeError('Cannot change colors after loading data')
        cm.ScalarMappable.set_cmap(self, cmap) 
Example 60
Project: neural-network-animation   Author: miloharper   File: image.py    MIT License 5 votes vote down vote up
def __init__(self, ax,
                 x=None,
                 y=None,
                 A=None,
                 cmap=None,
                 norm=None,
                 **kwargs
                 ):
        """
        cmap defaults to its rc setting

        cmap is a colors.Colormap instance
        norm is a colors.Normalize instance to map luminance to 0-1

        Additional kwargs are matplotlib.artist properties

        """
        martist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)
        self.axes = ax
        self._rgbacache = None
        # There is little point in caching the image itself because
        # it needs to be remade if the bbox or viewlim change,
        # so caching does help with zoom/pan/resize.
        self.update(kwargs)
        self.set_data(x, y, A) 
Example 61
Project: neural-network-animation   Author: miloharper   File: image.py    MIT License 5 votes vote down vote up
def changed(self):
        self._rgbacache = None
        cm.ScalarMappable.changed(self) 
Example 62
Project: neural-network-animation   Author: miloharper   File: image.py    MIT License 5 votes vote down vote up
def set_data(self, A):
        """Set the image array."""
        cm.ScalarMappable.set_array(self, cbook.safe_masked_invalid(A)) 
Example 63
Project: neural-network-animation   Author: miloharper   File: pyplot.py    MIT License 5 votes vote down vote up
def rcdefaults():
    matplotlib.rcdefaults()
    draw_if_interactive()


# The current "image" (ScalarMappable) is retrieved or set
# only via the pyplot interface using the following two
# functions: 
Example 64
Project: neural-network-animation   Author: miloharper   File: pyplot.py    MIT License 5 votes vote down vote up
def gci():
    """
    Get the current colorable artist.  Specifically, returns the
    current :class:`~matplotlib.cm.ScalarMappable` instance (image or
    patch collection), or *None* if no images or patch collections
    have been defined.  The commands :func:`~matplotlib.pyplot.imshow`
    and :func:`~matplotlib.pyplot.figimage` create
    :class:`~matplotlib.image.Image` instances, and the commands
    :func:`~matplotlib.pyplot.pcolor` and
    :func:`~matplotlib.pyplot.scatter` create
    :class:`~matplotlib.collections.Collection` instances.  The
    current image is an attribute of the current axes, or the nearest
    earlier axes in the current figure that contains an image.
    """
    return gcf()._gci() 
Example 65
Project: GraphicDesignPatternByPython   Author: Relph1119   File: image.py    MIT License 5 votes vote down vote up
def __init__(self, ax,
                 cmap=None,
                 norm=None,
                 interpolation=None,
                 origin=None,
                 filternorm=True,
                 filterrad=4.0,
                 resample=False,
                 **kwargs
                 ):
        """
        interpolation and cmap default to their rc settings

        cmap is a colors.Colormap instance
        norm is a colors.Normalize instance to map luminance to 0-1

        extent is data axes (left, right, bottom, top) for making image plots
        registered with data plots.  Default is to label the pixel
        centers with the zero-based row and column indices.

        Additional kwargs are matplotlib.artist properties

        """
        martist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)
        self._mouseover = True
        if origin is None:
            origin = rcParams['image.origin']
        self.origin = origin
        self.set_filternorm(filternorm)
        self.set_filterrad(filterrad)
        self.set_interpolation(interpolation)
        self.set_resample(resample)
        self.axes = ax

        self._imcache = None

        self.update(kwargs) 
Example 66
Project: DataHack2018   Author: InnovizTech   File: vis.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def color_pc(self, pc, coloring='reflectivity_and_label', colormap='pc_cmap'):
        """
        Generate coloring for point cloud based on multiple options
        :param pc: point cloud
        :param coloring: Coloring option. Supported: 'reflectivity', np.array of point cloud size x 4 with points colors
        :return:
        """
        if colormap is 'pc_cmap':
            colormap = pc_cmap

        points = pc[:, :3]
        color = np.zeros((len(pc), 4))
        color[:, -1] = 1.

        if isinstance(coloring, np.ndarray) and coloring.dtype == np.int and coloring.shape == (points.shape[0],):
            cmap = ListedColormap(
                ['w', 'magenta', 'orange', 'mediumspringgreen', 'deepskyblue', 'pink', 'y', 'g', 'r', 'purple', ])
            coloring = np.mod(coloring, len(cmap.colors))
            c = cm.ScalarMappable(cmap=cmap, norm=mcolors.Normalize(vmin=0, vmax=len(cmap.colors)-1))
            color = c.to_rgba(coloring)
        elif isinstance(coloring, np.ndarray):
            if coloring.shape == (points.shape[0], 4):
                color = coloring
            if coloring.shape == (points.shape[0], ):
                c = cm.ScalarMappable(cmap=colormap)
                color = c.to_rgba(coloring, norm=False)
        elif isinstance(coloring, collections.Callable):
            colors = coloring(points)
            c = cm.ScalarMappable(cmap=colormap)
            color = c.to_rgba(colors)
        elif coloring == 'reflectivity':
            reflectivity = pc[:, 3]
            reflectivity[reflectivity > 1] = 1
            c = cm.ScalarMappable(cmap=colormap)
            color = c.to_rgba(reflectivity, norm=False)
            color[reflectivity < 0] = np.array([1.0, 1.0, 1.0, 1.0])
        elif coloring == 'reflectivity_and_label':
            # pc_colors
            reflectivity = pc[:, 3]
            reflectivity[reflectivity > 1] = 1
            c = cm.ScalarMappable(cmap=colormap)
            color = c.to_rgba(reflectivity, norm=False)
            if pc.shape[-1] == 5:
                labels = pc[:, 4]
                labels_valid = labels[labels > 0]
                c = cm.ScalarMappable(cmap=label_cmap)
                color_labels = c.to_rgba(labels_valid, norm=True)
                color[labels > 0] = color_labels
        else:
            color = np.ones((points.shape[0], 4))
            color[:, -1] = 1.
        return color 
Example 67
Project: LaserTOF   Author: kyleuckert   File: collections.py    MIT License 4 votes vote down vote up
def __init__(self,
                 edgecolors=None,
                 facecolors=None,
                 linewidths=None,
                 linestyles='solid',
                 antialiaseds=None,
                 offsets=None,
                 transOffset=None,
                 norm=None,  # optional for ScalarMappable
                 cmap=None,  # ditto
                 pickradius=5.0,
                 hatch=None,
                 urls=None,
                 offset_position='screen',
                 zorder=1,
                 **kwargs
                 ):
        """
        Create a Collection

        %(Collection)s
        """
        artist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)
        # list of un-scaled dash patterns
        # this is needed scaling the dash pattern by linewidth
        self._us_linestyles = [(None, None)]
        # list of dash patterns
        self._linestyles = [(None, None)]
        # list of unbroadcast/scaled linewidths
        self._us_lw = [0]
        self._linewidths = [0]
        self._is_filled = True  # May be modified by set_facecolor().

        self.set_facecolor(facecolors)
        self.set_edgecolor(edgecolors)
        self.set_linewidth(linewidths)
        self.set_linestyle(linestyles)
        self.set_antialiased(antialiaseds)
        self.set_pickradius(pickradius)
        self.set_urls(urls)
        self.set_hatch(hatch)
        self.set_offset_position(offset_position)
        self.set_zorder(zorder)

        self._uniform_offsets = None
        self._offsets = np.array([[0, 0]], np.float_)
        if offsets is not None:
            offsets = np.asanyarray(offsets)
            offsets.shape = (-1, 2)             # Make it Nx2
            if transOffset is not None:
                self._offsets = offsets
                self._transOffset = transOffset
            else:
                self._uniform_offsets = offsets

        self._path_effects = None
        self.update(kwargs)
        self._paths = None 
Example 68
Project: LSDMappingTools   Author: LSDtopotools   File: plot_hillslope_morphology.py    MIT License 4 votes vote down vote up
def PlotChiElevationMChi(BasinID):
    
    # load the channel data
    ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)

    if (BasinChannelData.count == 0):
        print("No Channel Data for Basin ID " + str(BasinID))

    # isolate basin data
    BasinChannelData = ChannelData[ChannelData.basin_key == BasinID]
    MinimumChi = BasinChannelData.chi.min()
    MaximumMChi = BasinChannelData.m_chi.max()
    
    # how many segments are we dealing with?    
    Segments = BasinChannelData.segment_number.unique()
    
    # setup the figure
    Fig = CreateFigure()
    
    #choose colormap
    ColourMap = cm.viridis
    
    # Get the data columns for plotting
    for i in range(0, len(Segments)):
        #get data arrays
        Chi = ChannelData.chi[ChannelData.segment_number == Segments[i]]
        Elevation = ChannelData.elevation[ChannelData.segment_number == Segments[i]]
        SegmentedElevation = ChannelData.segmented_elevation[ChannelData.segment_number == Segments[i]]
        MChi = ChannelData.m_chi[ChannelData.segment_number == Segments[i]].unique()[0]
        
        #normalise chi by outlet chi
        Chi = Chi-MinimumChi
        #plot, colouring segments
        Colour = MChi/MaximumMChi
        plt.plot(Chi,Elevation,'k--',dashes=(2,2), lw=0.5,zorder=10)
        plt.plot(Chi, SegmentedElevation, '-', lw=2, c=ColourMap(Colour),zorder=9)
    
    # Finalise the figure
    plt.xlabel(r'$\chi$ (m)')
    plt.ylabel('Elevation (m)')
    plt.title('Basin ID ' + str(BasinID))
    plt.tight_layout()
    #add colourbar
    CAx = Fig.add_axes([0.15,0.8,0.4,0.05])
    m = cm.ScalarMappable(cmap=ColourMap)
    m.set_array(ChannelData.m_chi)
    plt.colorbar(m, cax=CAx,orientation='horizontal')
    plt.xlabel('$M_{\chi}$ m$^{0.64}$')
    #save output
    plt.savefig(PlotDirectory+FilenamePrefix + "_" + str(BasinID) + "_ChiElevMChi.png", dpi=300)
    plt.close() 
Example 69
Project: LSDMappingTools   Author: LSDtopotools   File: plot_hillslope_morphology.py    MIT License 4 votes vote down vote up
def PlotLongProfileMChi(BasinID):
    
    # load the channel data
    ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)

    # isolate basin data
    BasinChannelData = ChannelData[ChannelData.basin_key == BasinID]
    
    if (BasinChannelData.count == 0):
        print("No Channel Data for Basin ID " + str(BasinID))
        
    MinimumDistance = BasinChannelData.flow_distance.min()
    MaximumMChi = BasinChannelData.m_chi.max()
    
    # how many segments are we dealing with?    
    Segments = BasinChannelData.segment_number.unique()
    
    # setup the figure
    Fig = CreateFigure()
    
    #choose colormap
    ColourMap = cm.viridis
        
    # Get the data columns for plotting
    for i in range(0, len(Segments)):
        #get data arrays
        Dist = ChannelData.flow_distance[ChannelData.segment_number == Segments[i]]
        Elevation = ChannelData.elevation[ChannelData.segment_number == Segments[i]]
        SegmentedElevation = ChannelData.segmented_elevation[ChannelData.segment_number == Segments[i]]
        MChi = ChannelData.m_chi[ChannelData.segment_number == Segments[i]].unique()[0]
        
        #normalise distance by outlet distance
        Dist = Dist-MinimumDistance
        #plot, colouring segments
        Colour = MChi/MaximumMChi
        plt.plot(Dist/1000,Elevation,'k--',dashes=(2,2), lw=0.5,zorder=10)
        plt.plot(Dist/1000, SegmentedElevation, '-', lw=2, c=ColourMap(Colour),zorder=9)
    
    # Finalise the figure
    plt.xlabel('Distance (km)')
    plt.ylabel('Elevation (m)')
    plt.title('Basin ID ' + str(BasinID))
    plt.tight_layout()
    #add colourbar
    CAx = Fig.add_axes([0.15,0.8,0.4,0.05])
    m = cm.ScalarMappable(cmap=ColourMap)
    m.set_array(ChannelData.m_chi)
    plt.colorbar(m, cax=CAx,orientation='horizontal')
    plt.xlabel('$M_{\chi}$ m$^{0.64}$')
    #save output
    plt.savefig(PlotDirectory+FilenamePrefix + "_" + str(BasinID) + "_LongProfMChi.png", dpi=300)
    plt.close() 
Example 70
Project: LSDMappingTools   Author: LSDtopotools   File: plot_hillslope_morphology.py    MIT License 4 votes vote down vote up
def PlotEStarRStar(Basin, Sc=0.71):
    """
    MDH
    """
    
    Data = CalculateEStarRStar(Basin)
    
    # setup the figure
    Fig = CreateFigure(AspectRatio=1.2)
        
    #choose colormap
    ColourMap = cm.viridis

    #Plot analytical relationship
    PlotEStarRStarTheoretical()
    
    # colour code by flow length
    MinFlowLength = Data.FlowLength.min()
    Data.FlowLength = Data.FlowLength-MinFlowLength
    MaxFlowLength = Data.FlowLength.max()
    colours = (Data.FlowLength/MaxFlowLength)
    
    #plot the data
    plt.loglog()
    
    # Error bars with colours but faded (alpha)
    for i, row in Data.iterrows(): 
        EStarErr = np.array([[row.EStarLower],[row.EStarUpper]])
        RStarErr = np.array([[row.RStarLower],[row.RStarUpper]])
        plt.plot([row.EStar,row.EStar],RStarErr,'-', lw=1, color=ColourMap(colours[i]), alpha=0.5,zorder=9)
        plt.plot(EStarErr,[row.RStar,row.RStar],'-', lw=1, color=ColourMap(colours[i]), alpha=0.5,zorder=9)
        plt.plot(row.EStar,row.RStar,'o',ms=4,color=ColourMap(colours[i]),zorder=32)

    # Finalise the figure
    plt.xlabel('$E^*={{-2\:C_{HT}\:L_H}/{S_C}}$')
    plt.ylabel('$R^*=S/S_C$')
    plt.xlim(0.1,1000)
    plt.ylim(0.01,1.5)
        
    # add colour bar
    m = cm.ScalarMappable(cmap=ColourMap)
    m.set_array(Data.FlowLength)
    cbar = plt.colorbar(m)
    tick_locator = ticker.MaxNLocator(nbins=5)
    cbar.locator = tick_locator
    cbar.update_ticks()
    cbar.set_label('Distance to Outlet (m)')
    
    plt.suptitle("Basin "+str(Basin)+" Dimensionless Hillslope Morphology")
    plt.tight_layout(rect=[0, 0.03, 1, 0.95])
    plt.savefig(PlotDirectory+FilenamePrefix + "_" + "%02d" % Basin + "_EStarRStar.png", dpi=300)
    plt.close(Fig) 
Example 71
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_HillslopeMorphology.py    MIT License 4 votes vote down vote up
def PlotKsnAgainstRStar(DataDirectory, FilenamePrefix, PlotDirectory):
    """
    Function to plot median Ksn against R* for a series of basins

    Author: FJC
    """

    # SMM: What generates this file?? I don't have it.
    input_csv = PlotDirectory+FilenamePrefix+'_basin_hillslope_data.csv'
    df = pd.read_csv(input_csv)

    # linregress
    slope, intercept, r_value, p_value, std_err = stats.linregress(df['mchi_median'],df['Rstar_median'])
    print(slope, intercept, r_value, p_value)
    x = np.linspace(0, 200, 100)
    new_y = slope*x + intercept

    # set up the figure
    fig, ax = plt.subplots(nrows=1, ncols=1, sharex=True, figsize=(5,5))

    ax.scatter(df['mchi_median'], df['Rstar_median'], c=df['basin_keys'], s=50, edgecolors='k', zorder=100, cmap=cm.viridis)
    ax.errorbar(df['mchi_median'], df['Rstar_median'], xerr=[df['mchi_lower_err'], df['mchi_upper_err']], yerr=[df['Rstar_lower_err'], df['Rstar_upper_err']], fmt='o', ecolor='0.5',markersize=1,mfc='white',mec='k')
    # ax.text(0.55, 0.1, '$y = $'+str(np.round(slope,4))+'$x + $'+str(np.round(intercept,2))+'\n$R^2 = $'+str(np.round(r_value,2))+'\n$p = $'+str(p_value), fontsize=9, color='black', transform=ax.transAxes)
    ax.plot(x, new_y, c='0.5', ls='--')
    ax.set_xlim(0,100)

    ax.set_xlabel('$k_{sn}$')
    ax.set_ylabel('$R*$')

    plt.subplots_adjust(left=0.15,right=0.85, bottom=0.1, top=0.95)
    CAx = fig.add_axes([0.87,0.1,0.02,0.85])
    m = cm.ScalarMappable(cmap=cm.viridis)
    m.set_array(df['basin_keys'])
    plt.colorbar(m, cax=CAx,orientation='vertical', label='Basin key')

    #plt.tight_layout()

    #save output
    plt.savefig(PlotDirectory+FilenamePrefix +"_ksn_vs_rstar.png", dpi=300)
    plt.clf()


# This seems to do the same as the PlotEStarRStarWithinBasin function!!!
# However it is not working since I don't have the _basin_hillslope_data.csv' file 
Example 72
Project: CornerPlot   Author: anguswilliams91   File: corner_plot.py    MIT License 4 votes vote down vote up
def confidence_2d(xsamples,ysamples,ax=None,weights=None,intervals=None,nbins=20,linecolor='k',\
                   cmap="Blues",filled=False,linewidth=1., gradient=False, scatter=False, \
                   scatter_size=2.,scatter_color='k', scatter_alpha=0.5 ):
    """Draw confidence intervals at the levels asked from a 2d sample of points (e.g. 
        output of MCMC)"""

    if intervals is None:
        intervals  = 1.0 - np.exp(-0.5 * np.array([0., 1., 2.]) ** 2)
    H,yedges,xedges = np.histogram2d(ysamples,xsamples,bins=nbins,weights=weights)

    #get the contour levels
    if not scatter:
        try:
            h = np.sort(H.flatten())[::-1]
            cdf = np.cumsum(h)/np.cumsum(h)[-1]
            v = np.array([h[ cdf<=li ][-1] for li in intervals[1:]])[::-1]
            v = np.append(v,h[0])
            if not np.all(np.diff(v)>0.):
                raise RuntimeError() 
        except:
            cNorm = colors.Normalize(vmin=0.,vmax=1.)
            scalarMap = cm.ScalarMappable(norm=cNorm,cmap=cmap)
            cVal = scalarMap.to_rgba(0.65)
            ax.plot(xsamples,ysamples,'o',mec='none',mfc=cVal,alpha=scatter_alpha,ms=scatter_size,\
                    rasterized=True)
            ax.set_xlim((np.min(xedges),np.max(xedges)))
            ax.set_ylim((np.min(yedges),np.max(yedges)))
            return None


    else:
        #if the contour levels are not monotonically increasing, just do a scatter plot
        if ax is None:
            fig,ax = plt.subplots
        ax.plot(xsamples,ysamples,'o',mec='none',mfc=scatter_color,alpha=scatter_alpha,ms=scatter_size,\
                rasterized=True)
        ax.set_xlim((np.min(xedges),np.max(xedges)))
        ax.set_ylim((np.min(yedges),np.max(yedges)))
        return None

    xc = np.array([.5*(xedges[i]+xedges[i+1]) for i in np.arange(nbins)]) #bin centres
    yc = np.array([.5*(yedges[i]+yedges[i+1]) for i in np.arange(nbins)])

    xx,yy = np.meshgrid(xc,yc)

    if filled:
        if gradient:
            ax.imshow(H,cmap=cmap,origin='lower',extent=(np.min(xedges),np.max(xedges),np.min(yedges),\
                      np.max(yedges)),interpolation='bicubic',aspect='auto')
        else:
            ax.contourf(xx,yy,H,levels=v,cmap=cmap)
        ax.contour(xx,yy,H,levels=v,colors=linecolor,extend='max',linewidths=linewidth)
    else:
        ax.contour(xx,yy,H,levels=v,colors=linecolor,linewidths=linewidth)        

    return None 
Example 73
Project: rsz   Author: gillenbrown   File: plotting.py    MIT License 4 votes vote down vote up
def add_all_models(fig, ax, steal_axs, cfg, models):
    """
    Adds the RS models to the given axis, adding a colorbar to code redshift.

    The fig and ax should be obtained by calling cmd(). The models will be
    meaningless on any other plot.

    :param fig: Figure containing the plots.
    :param ax: CMD axis the models will be drawn onto.
    :param steal_axs: List of axes that will be resized to make room for the
                      colorbar. If you made labels in Vega, those axes will
                      need to be passed to this too.
    :param cfg: Configuration dictionary for the bands of interest.
    :param models: Dictionary holding models. This is created in the cluster
                   class.
    :return: none, but fig and ax are modified by adding the models and
             colorbar, as well as resizing the axes in steal_axs.
    """

    # get the model predictions for the correct band combo
    models = models[cfg["color"]]

    # set the colormap, so we can color code lines by redshift
    cmap = plt.get_cmap("RdYlBu_r")
    # some other decent colormaps: coolwarm, bwr, jet, RdBu_r, RdYlBu_r,
    # Spectral_r, rainbow
    # normalize the colormap
    c_norm = mplcol.Normalize(vmin=np.float64(min(models)),
                              vmax=np.float64(max(models)))
    scalar_map = cmx.ScalarMappable(norm=c_norm, cmap=cmap)

    for z in models:
        # use the scalar map to get the color for this redshift.
        color_val = scalar_map.to_rgba(float(z))  # have to convert to float
        # to make it play nice with the floats used in that function

        # plot the line for this model
        add_one_model(ax, models[z], color_val)

    # add the colorbar
    scalar_map.set_array([])  # Don't know what this does
    cb = fig.colorbar(mappable=scalar_map, ax=steal_axs, pad=0.15,
                      fraction=0.05, anchor=(1.0, 1.0))
    cb.set_label("Redshift")
    cb.set_ticks(np.arange(0, 3, 0.1)) 
Example 74
Project: Computable   Author: ktraunmueller   File: collections.py    MIT License 4 votes vote down vote up
def __init__(self,
                 edgecolors=None,
                 facecolors=None,
                 linewidths=None,
                 linestyles='solid',
                 antialiaseds=None,
                 offsets=None,
                 transOffset=None,
                 norm=None,  # optional for ScalarMappable
                 cmap=None,  # ditto
                 pickradius=5.0,
                 hatch=None,
                 urls=None,
                 offset_position='screen',
                 zorder=1,
                 **kwargs
                 ):
        """
        Create a Collection

        %(Collection)s
        """
        artist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)

        self.set_edgecolor(edgecolors)
        self.set_facecolor(facecolors)
        self.set_linewidth(linewidths)
        self.set_linestyle(linestyles)
        self.set_antialiased(antialiaseds)
        self.set_pickradius(pickradius)
        self.set_urls(urls)
        self.set_hatch(hatch)
        self.set_offset_position(offset_position)
        self.set_zorder(zorder)

        self._uniform_offsets = None
        self._offsets = np.array([[0, 0]], np.float_)
        if offsets is not None:
            offsets = np.asanyarray(offsets)
            offsets.shape = (-1, 2)             # Make it Nx2
            if transOffset is not None:
                self._offsets = offsets
                self._transOffset = transOffset
            else:
                self._uniform_offsets = offsets

        self._path_effects = None
        self.update(kwargs)
        self._paths = None 
Example 75
Project: Computable   Author: ktraunmueller   File: collections.py    MIT License 4 votes vote down vote up
def __init__(self, patches, match_original=False, **kwargs):
        """
        *patches*
            a sequence of Patch objects.  This list may include
            a heterogeneous assortment of different patch types.

        *match_original*
            If True, use the colors and linewidths of the original
            patches.  If False, new colors may be assigned by
            providing the standard collection arguments, facecolor,
            edgecolor, linewidths, norm or cmap.

        If any of *edgecolors*, *facecolors*, *linewidths*,
        *antialiaseds* are None, they default to their
        :data:`matplotlib.rcParams` patch setting, in sequence form.

        The use of :class:`~matplotlib.cm.ScalarMappable` is optional.
        If the :class:`~matplotlib.cm.ScalarMappable` matrix _A is not
        None (ie a call to set_array has been made), at draw time a
        call to scalar mappable will be made to set the face colors.
        """

        if match_original:
            def determine_facecolor(patch):
                if patch.get_fill():
                    return patch.get_facecolor()
                return [0, 0, 0, 0]

            facecolors = [determine_facecolor(p) for p in patches]
            edgecolors = [p.get_edgecolor() for p in patches]
            linewidths = [p.get_linewidth() for p in patches]
            linestyles = [p.get_linestyle() for p in patches]
            antialiaseds = [p.get_antialiased() for p in patches]

            Collection.__init__(
                self,
                edgecolors=edgecolors,
                facecolors=facecolors,
                linewidths=linewidths,
                linestyles=linestyles,
                antialiaseds=antialiaseds)
        else:
            Collection.__init__(self, **kwargs)

        self.set_paths(patches) 
Example 76
Project: Computable   Author: ktraunmueller   File: image.py    MIT License 4 votes vote down vote up
def __init__(self, ax,
                 cmap=None,
                 norm=None,
                 interpolation=None,
                 origin=None,
                 filternorm=1,
                 filterrad=4.0,
                 resample=False,
                 **kwargs
                 ):
        """
        interpolation and cmap default to their rc settings

        cmap is a colors.Colormap instance
        norm is a colors.Normalize instance to map luminance to 0-1

        extent is data axes (left, right, bottom, top) for making image plots
        registered with data plots.  Default is to label the pixel
        centers with the zero-based row and column indices.

        Additional kwargs are matplotlib.artist properties

        """
        martist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)

        if origin is None:
            origin = rcParams['image.origin']
        self.origin = origin
        self.set_filternorm(filternorm)
        self.set_filterrad(filterrad)
        self._filterrad = filterrad

        self.set_interpolation(interpolation)
        self.set_resample(resample)
        self.axes = ax

        self._imcache = None

        # this is an experimental attribute, if True, unsampled image
        # will be drawn using the affine transform that are
        # appropriately skewed so that the given position
        # corresponds to the actual position in the coordinate. -JJL
        self._image_skew_coordinate = None

        self.update(kwargs) 
Example 77
Project: GProject   Author: fnbellomo   File: Plot.py    GNU General Public License v2.0 4 votes vote down vote up
def __init__(self, grav):
        """
        Create the class

        Parameters
        ----------
        grav : objects
              Gravitational object

        If grav.do_plot == True, are going to display the plots. 

        """

        self.grav = grav
        self.do_plot = self.grav.do_plot
        self.number_body = len(self.grav.bodies)
        self.bodies_range = range(self.number_body)

        #Check if are some img in the path.
        #If exist, delete all
        self.img_path = './Gravitation/Animation/Img/'
        if os.path.isdir(self.img_path):
            shutil.rmtree(self.img_path)
            os.mkdir(self.img_path)
        else:
            os.mkdir(self.img_path)

        #img_num va a ser un contador que va a aumentar, con el cual vamos a guardar
        #cada imagen que generamos para luego hacer una animacion.
        self.img_num = 1


        self.mass = [grav.bodies[i].obj_mass for i in range(len(grav.bodies))]
        self.mass_max = max(self.mass)
        self.rad  = [sqrt(pow(grav.bodies[i].obj_position[0],2)+pow(grav.bodies[i].obj_position[1],2)) for i in range(len(grav.bodies))]
        self.rad_max = max(self.rad)
        self.circle_radio = [ self.rad_max*0.1*m/self.mass_max for m in self.mass]
        
        #To make that the same body have the same color
        curves = [np.random.random(20) for i in self.bodies_range]
        jet = cm = plt.get_cmap('jet') 
        cNorm  = colors.Normalize(vmin=0, vmax=self.bodies_range[-1])
        self.scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
	    
        #Setup the plot
        self.fig, self.axes = plt.subplots(figsize=(12,12))
        
        if self.do_plot == True:
            #Turn interactive mode on.
            plt.ion()
        else:
            plt.ioff()

        self.base()
        #self.update(0) 
Example 78
Project: neural-network-animation   Author: miloharper   File: collections.py    MIT License 4 votes vote down vote up
def __init__(self,
                 edgecolors=None,
                 facecolors=None,
                 linewidths=None,
                 linestyles='solid',
                 antialiaseds=None,
                 offsets=None,
                 transOffset=None,
                 norm=None,  # optional for ScalarMappable
                 cmap=None,  # ditto
                 pickradius=5.0,
                 hatch=None,
                 urls=None,
                 offset_position='screen',
                 zorder=1,
                 **kwargs
                 ):
        """
        Create a Collection

        %(Collection)s
        """
        artist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)

        self.set_edgecolor(edgecolors)
        self.set_facecolor(facecolors)
        self.set_linewidth(linewidths)
        self.set_linestyle(linestyles)
        self.set_antialiased(antialiaseds)
        self.set_pickradius(pickradius)
        self.set_urls(urls)
        self.set_hatch(hatch)
        self.set_offset_position(offset_position)
        self.set_zorder(zorder)

        self._uniform_offsets = None
        self._offsets = np.array([[0, 0]], np.float_)
        if offsets is not None:
            offsets = np.asanyarray(offsets)
            offsets.shape = (-1, 2)             # Make it Nx2
            if transOffset is not None:
                self._offsets = offsets
                self._transOffset = transOffset
            else:
                self._uniform_offsets = offsets

        self._path_effects = None
        self.update(kwargs)
        self._paths = None 
Example 79
Project: neural-network-animation   Author: miloharper   File: collections.py    MIT License 4 votes vote down vote up
def __init__(self, patches, match_original=False, **kwargs):
        """
        *patches*
            a sequence of Patch objects.  This list may include
            a heterogeneous assortment of different patch types.

        *match_original*
            If True, use the colors and linewidths of the original
            patches.  If False, new colors may be assigned by
            providing the standard collection arguments, facecolor,
            edgecolor, linewidths, norm or cmap.

        If any of *edgecolors*, *facecolors*, *linewidths*,
        *antialiaseds* are None, they default to their
        :data:`matplotlib.rcParams` patch setting, in sequence form.

        The use of :class:`~matplotlib.cm.ScalarMappable` is optional.
        If the :class:`~matplotlib.cm.ScalarMappable` matrix _A is not
        None (i.e., a call to set_array has been made), at draw time a
        call to scalar mappable will be made to set the face colors.
        """

        if match_original:
            def determine_facecolor(patch):
                if patch.get_fill():
                    return patch.get_facecolor()
                return [0, 0, 0, 0]

            facecolors = [determine_facecolor(p) for p in patches]
            edgecolors = [p.get_edgecolor() for p in patches]
            linewidths = [p.get_linewidth() for p in patches]
            linestyles = [p.get_linestyle() for p in patches]
            antialiaseds = [p.get_antialiased() for p in patches]

            Collection.__init__(
                self,
                edgecolors=edgecolors,
                facecolors=facecolors,
                linewidths=linewidths,
                linestyles=linestyles,
                antialiaseds=antialiaseds)
        else:
            Collection.__init__(self, **kwargs)

        self.set_paths(patches) 
Example 80
Project: neural-network-animation   Author: miloharper   File: image.py    MIT License 4 votes vote down vote up
def __init__(self, ax,
                 cmap=None,
                 norm=None,
                 interpolation=None,
                 origin=None,
                 filternorm=1,
                 filterrad=4.0,
                 resample=False,
                 **kwargs
                 ):
        """
        interpolation and cmap default to their rc settings

        cmap is a colors.Colormap instance
        norm is a colors.Normalize instance to map luminance to 0-1

        extent is data axes (left, right, bottom, top) for making image plots
        registered with data plots.  Default is to label the pixel
        centers with the zero-based row and column indices.

        Additional kwargs are matplotlib.artist properties

        """
        martist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)

        if origin is None:
            origin = rcParams['image.origin']
        self.origin = origin
        self.set_filternorm(filternorm)
        self.set_filterrad(filterrad)
        self._filterrad = filterrad

        self.set_interpolation(interpolation)
        self.set_resample(resample)
        self.axes = ax

        self._imcache = None

        # this is an experimental attribute, if True, unsampled image
        # will be drawn using the affine transform that are
        # appropriately skewed so that the given position
        # corresponds to the actual position in the coordinate. -JJL
        self._image_skew_coordinate = None

        self.update(kwargs)