Python matplotlib.colors.PowerNorm() Examples

The following are 20 code examples of matplotlib.colors.PowerNorm(). 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.colors , or try the search function .
Example #1
Source File: Demo_Matplotlib_Browser_Paned.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def ExploringNormalizations():
    import matplotlib.pyplot as plt
    import matplotlib.colors as mcolors
    import numpy as np
    from numpy.random import multivariate_normal

    data = np.vstack([
        multivariate_normal([10, 10], [[3, 2], [2, 3]], size=100000),
        multivariate_normal([30, 20], [[2, 3], [1, 3]], size=1000)
    ])

    gammas = [0.8, 0.5, 0.3]

    fig, axes = plt.subplots(nrows=2, ncols=2)

    axes[0, 0].set_title('Linear normalization')
    axes[0, 0].hist2d(data[:, 0], data[:, 1], bins=100)

    for ax, gamma in zip(axes.flat[1:], gammas):
        ax.set_title(r'Power law $(\gamma=%1.1f)$' % gamma)
        ax.hist2d(data[:, 0], data[:, 1],
                  bins=100, norm=mcolors.PowerNorm(gamma))

    fig.tight_layout()
    return fig 
Example #2
Source File: Demo_Matplotlib_Browser.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def ExploringNormalizations():
    import matplotlib.pyplot as plt
    import matplotlib.colors as mcolors
    import numpy as np
    from numpy.random import multivariate_normal

    data = np.vstack([
        multivariate_normal([10, 10], [[3, 2], [2, 3]], size=100000),
        multivariate_normal([30, 20], [[2, 3], [1, 3]], size=1000)
    ])

    gammas = [0.8, 0.5, 0.3]

    fig, axes = plt.subplots(nrows=2, ncols=2)

    axes[0, 0].set_title('Linear normalization')
    axes[0, 0].hist2d(data[:, 0], data[:, 1], bins=100)

    for ax, gamma in zip(axes.flat[1:], gammas):
        ax.set_title(r'Power law $(\gamma=%1.1f)$' % gamma)
        ax.hist2d(data[:, 0], data[:, 1],
                  bins=100, norm=mcolors.PowerNorm(gamma))

    fig.tight_layout()
    return fig 
Example #3
Source File: Demo_Matplotlib_Browser_Paned.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def ExploringNormalizations():
    import matplotlib.pyplot as plt
    import matplotlib.colors as mcolors
    import numpy as np
    from numpy.random import multivariate_normal

    data = np.vstack([
        multivariate_normal([10, 10], [[3, 2], [2, 3]], size=100000),
        multivariate_normal([30, 20], [[2, 3], [1, 3]], size=1000)
    ])

    gammas = [0.8, 0.5, 0.3]

    fig, axes = plt.subplots(nrows=2, ncols=2)

    axes[0, 0].set_title('Linear normalization')
    axes[0, 0].hist2d(data[:, 0], data[:, 1], bins=100)

    for ax, gamma in zip(axes.flat[1:], gammas):
        ax.set_title(r'Power law $(\gamma=%1.1f)$' % gamma)
        ax.hist2d(data[:, 0], data[:, 1],
                  bins=100, norm=mcolors.PowerNorm(gamma))

    fig.tight_layout()
    return fig 
Example #4
Source File: Demo_Matplotlib_Browser.py    From PySimpleGUI with GNU Lesser General Public License v3.0 6 votes vote down vote up
def ExploringNormalizations():
    import matplotlib.pyplot as plt
    import matplotlib.colors as mcolors
    import numpy as np
    from numpy.random import multivariate_normal

    data = np.vstack([
        multivariate_normal([10, 10], [[3, 2], [2, 3]], size=100000),
        multivariate_normal([30, 20], [[2, 3], [1, 3]], size=1000)
    ])

    gammas = [0.8, 0.5, 0.3]

    fig, axes = plt.subplots(nrows=2, ncols=2)

    axes[0, 0].set_title('Linear normalization')
    axes[0, 0].hist2d(data[:, 0], data[:, 1], bins=100)

    for ax, gamma in zip(axes.flat[1:], gammas):
        ax.set_title(r'Power law $(\gamma=%1.1f)$' % gamma)
        ax.hist2d(data[:, 0], data[:, 1],
                  bins=100, norm=mcolors.PowerNorm(gamma))

    fig.tight_layout()
    return fig 
Example #5
Source File: test_colors.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_ndarray_subclass_norm(recwarn):
    # Emulate an ndarray subclass that handles units
    # which objects when adding or subtracting with other
    # arrays. See #6622 and #8696
    class MyArray(np.ndarray):
        def __isub__(self, other):
            raise RuntimeError

        def __add__(self, other):
            raise RuntimeError

    data = np.arange(-10, 10, 1, dtype=float)
    data.shape = (10, 2)
    mydata = data.view(MyArray)

    for norm in [mcolors.Normalize(), mcolors.LogNorm(),
                 mcolors.SymLogNorm(3, vmax=5, linscale=1),
                 mcolors.Normalize(vmin=mydata.min(), vmax=mydata.max()),
                 mcolors.SymLogNorm(3, vmin=mydata.min(), vmax=mydata.max()),
                 mcolors.PowerNorm(1)]:
        assert_array_equal(norm(mydata), norm(data))
        fig, ax = plt.subplots()
        ax.imshow(mydata, norm=norm)
        fig.canvas.draw()
        if isinstance(norm, mcolors.PowerNorm):
            assert len(recwarn) == 1
            warn = recwarn.pop(UserWarning)
            assert ('Power-law scaling on negative values is ill-defined'
                    in str(warn.message))
        else:
            assert len(recwarn) == 0
        recwarn.clear() 
Example #6
Source File: test_colors.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_PowerNorm():
    a = np.array([0, 0.5, 1, 1.5], dtype=float)
    pnorm = mcolors.PowerNorm(1)
    norm = mcolors.Normalize()
    assert_array_almost_equal(norm(a), pnorm(a))

    a = np.array([-0.5, 0, 2, 4, 8], dtype=float)
    expected = [0, 0, 1/16, 1/4, 1]
    pnorm = mcolors.PowerNorm(2, vmin=0, vmax=8)
    assert_array_almost_equal(pnorm(a), expected)
    assert pnorm(a[0]) == expected[0]
    assert pnorm(a[2]) == expected[2]
    assert_array_almost_equal(a[1:], pnorm.inverse(pnorm(a))[1:])

    # Clip = True
    a = np.array([-0.5, 0, 1, 8, 16], dtype=float)
    expected = [0, 0, 0, 1, 1]
    pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=True)
    assert_array_almost_equal(pnorm(a), expected)
    assert pnorm(a[0]) == expected[0]
    assert pnorm(a[-1]) == expected[-1]

    # Clip = True at call time
    a = np.array([-0.5, 0, 1, 8, 16], dtype=float)
    expected = [0, 0, 0, 1, 1]
    pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=False)
    assert_array_almost_equal(pnorm(a, clip=True), expected)
    assert pnorm(a[0], clip=True) == expected[0]
    assert pnorm(a[-1], clip=True) == expected[-1] 
Example #7
Source File: test_colorbar.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_colorbar_powernorm_extension():
    # Test that colorbar with powernorm is extended correctly
    f, ax = plt.subplots()
    cb = ColorbarBase(ax, norm=PowerNorm(gamma=0.5, vmin=0.0, vmax=1.0),
                      orientation='vertical', extend='both')
    assert cb._values[0] >= 0.0 
Example #8
Source File: test_colors.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_ndarray_subclass_norm(recwarn):
    # Emulate an ndarray subclass that handles units
    # which objects when adding or subtracting with other
    # arrays. See #6622 and #8696
    class MyArray(np.ndarray):
        def __isub__(self, other):
            raise RuntimeError

        def __add__(self, other):
            raise RuntimeError

    data = np.arange(-10, 10, 1, dtype=float)
    data.shape = (10, 2)
    mydata = data.view(MyArray)

    for norm in [mcolors.Normalize(), mcolors.LogNorm(),
                 mcolors.SymLogNorm(3, vmax=5, linscale=1),
                 mcolors.Normalize(vmin=mydata.min(), vmax=mydata.max()),
                 mcolors.SymLogNorm(3, vmin=mydata.min(), vmax=mydata.max()),
                 mcolors.PowerNorm(1)]:
        assert_array_equal(norm(mydata), norm(data))
        fig, ax = plt.subplots()
        ax.imshow(mydata, norm=norm)
        fig.canvas.draw()
        assert len(recwarn) == 0
        recwarn.clear() 
Example #9
Source File: test_colors.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_PowerNorm_translation_invariance():
    a = np.array([0, 1/2, 1], dtype=float)
    expected = [0, 1/8, 1]
    pnorm = mcolors.PowerNorm(vmin=0, vmax=1, gamma=3)
    assert_array_almost_equal(pnorm(a), expected)
    pnorm = mcolors.PowerNorm(vmin=-2, vmax=-1, gamma=3)
    assert_array_almost_equal(pnorm(a - 2), expected) 
Example #10
Source File: test_colors.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_PowerNorm():
    a = np.array([0, 0.5, 1, 1.5], dtype=float)
    pnorm = mcolors.PowerNorm(1)
    norm = mcolors.Normalize()
    assert_array_almost_equal(norm(a), pnorm(a))

    a = np.array([-0.5, 0, 2, 4, 8], dtype=float)
    expected = [0, 0, 1/16, 1/4, 1]
    pnorm = mcolors.PowerNorm(2, vmin=0, vmax=8)
    assert_array_almost_equal(pnorm(a), expected)
    assert pnorm(a[0]) == expected[0]
    assert pnorm(a[2]) == expected[2]
    assert_array_almost_equal(a[1:], pnorm.inverse(pnorm(a))[1:])

    # Clip = True
    a = np.array([-0.5, 0, 1, 8, 16], dtype=float)
    expected = [0, 0, 0, 1, 1]
    pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=True)
    assert_array_almost_equal(pnorm(a), expected)
    assert pnorm(a[0]) == expected[0]
    assert pnorm(a[-1]) == expected[-1]

    # Clip = True at call time
    a = np.array([-0.5, 0, 1, 8, 16], dtype=float)
    expected = [0, 0, 0, 1, 1]
    pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=False)
    assert_array_almost_equal(pnorm(a, clip=True), expected)
    assert pnorm(a[0], clip=True) == expected[0]
    assert pnorm(a[-1], clip=True) == expected[-1] 
Example #11
Source File: cmap.py    From artview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def update_colormap(self):
        '''Get colormap from GUI.'''
        self.cmap['lock'] = self.lock_box.isChecked()
        idx = self.norm_type.currentIndex()

        self.cmap['vmin'] = float(self.ent_vmin.text())
        self.cmap['vmax'] = float(self.ent_vmax.text())

        if idx == 0:
            self.cmap['norm'] = None
        elif idx == 1:
            self.cmap['norm'] = colors.Normalize(vmin=self.cmap['vmin'],
                                                 vmax=self.cmap['vmax'])
        elif idx == 2:
            self.cmap['norm'] = colors.LogNorm(vmin=self.cmap['vmin'],
                                               vmax=self.cmap['vmax'])
        elif idx == 3:
            self.cmap['norm'] = colors.SymLogNorm(
                linthresh=float(self.ent_linthresh.text()),
                linscale=float(self.ent_linscale.text()),
                vmin=self.cmap['vmin'],
                vmax=self.cmap['vmax'])
        elif idx == 4:
            self.cmap['norm'] = colors.PowerNorm(
                gamma=float(self.ent_gamma.text()),
                vmin=self.cmap['vmin'],
                vmax=self.cmap['vmax'])
        elif idx == 5:
            bounds = self.get_bounds()
            self.cmap['norm'] = colors.BoundaryNorm(bounds,
                                                    ncolors=256)
        self.plot() 
Example #12
Source File: cmap.py    From artview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot(self):
        '''Replot the colorbar.'''
        if self.cmap is None:
            return

        self.ax.cla()
        self.cax.cla()
        cmap = self.cmap
        if 'norm' not in cmap or cmap['norm'] is None:
            self.norm_type.setCurrentIndex(0)
        else:
            norm_name = cmap['norm'].__class__.__name__
            if norm_name == 'Normalize':
                self.norm_type.setCurrentIndex(1)
            elif norm_name == 'LogNorm':
                self.norm_type.setCurrentIndex(2)
            elif norm_name == 'SymLogNorm':
                self.norm_type.setCurrentIndex(3)
            elif norm_name == 'PowerNorm':
                self.norm_type.setCurrentIndex(4)
            elif norm_name == 'BoundaryNorm':
                self.norm_type.setCurrentIndex(5)

        if cmap is not None:
            if 'norm' in cmap:
                norm = cmap['norm']
            else:
                norm = None
            im = self.ax.imshow(gradient, aspect='auto', cmap=cmap['cmap'],
                                vmin=cmap['vmin'], vmax=cmap['vmax'],
                                norm=norm)
            plt.colorbar(im, cax=self.cax)

        self.canvas.draw() 
Example #13
Source File: test_colors.py    From ImageFusion with MIT License 5 votes vote down vote up
def test_PowerNorm():
    a = np.array([0, 0.5, 1, 1.5], dtype=np.float)
    pnorm = mcolors.PowerNorm(1)
    norm = mcolors.Normalize()
    assert_array_almost_equal(norm(a), pnorm(a))

    a = np.array([-0.5, 0, 2, 4, 8], dtype=np.float)
    expected = [0, 0, 1/16, 1/4, 1]
    pnorm = mcolors.PowerNorm(2, vmin=0, vmax=8)
    assert_array_almost_equal(pnorm(a), expected)
    assert_equal(pnorm(a[0]), expected[0])
    assert_equal(pnorm(a[2]), expected[2])
    assert_array_almost_equal(a[1:], pnorm.inverse(pnorm(a))[1:])

    # Clip = True
    a = np.array([-0.5, 0, 1, 8, 16], dtype=np.float)
    expected = [0, 0, 0, 1, 1]
    pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=True)
    assert_array_almost_equal(pnorm(a), expected)
    assert_equal(pnorm(a[0]), expected[0])
    assert_equal(pnorm(a[-1]), expected[-1])

    # Clip = True at call time
    a = np.array([-0.5, 0, 1, 8, 16], dtype=np.float)
    expected = [0, 0, 0, 1, 1]
    pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=False)
    assert_array_almost_equal(pnorm(a, clip=True), expected)
    assert_equal(pnorm(a[0], clip=True), expected[0])
    assert_equal(pnorm(a[-1], clip=True), expected[-1]) 
Example #14
Source File: analysisfigure.py    From ray-optics with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, fig, gs, ray_list,
                 user_scale_value=0.1, scale_type='fit',
                 yaxis_ticks_position='left', dsp_typ='hist2d',
                 **kwargs):
        self.fig = fig
        self.fig.subplots.append(self)

        self.gs = gs
        self.ray_list = ray_list
        self.dsp_typ = dsp_typ

        if 'title' in kwargs:
            self.title = kwargs.pop('title', None)

        if 'norm' in kwargs:
            self.norm = kwargs.pop('norm', None)
        else:
            gamma = kwargs.pop('gamma', 0.5)
            vmax = kwargs.get('vmax') if 'vmax' in kwargs else None
            self.norm = PowerNorm(gamma, vmin=0., vmax=vmax)

        self.plot_kwargs = kwargs

        self.user_scale_value = user_scale_value
        self.scale_type = scale_type
        self.yaxis_ticks_position = yaxis_ticks_position

        self.update_data() 
Example #15
Source File: test_colorbar.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_colorbar_powernorm_extension():
    # Test that colorbar with powernorm is extended correctly
    f, ax = plt.subplots()
    cb = ColorbarBase(ax, norm=PowerNorm(gamma=0.5, vmin=0.0, vmax=1.0),
                      orientation='vertical', extend='both')
    assert cb._values[0] >= 0.0 
Example #16
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ndarray_subclass_norm(recwarn):
    # Emulate an ndarray subclass that handles units
    # which objects when adding or subtracting with other
    # arrays. See #6622 and #8696
    class MyArray(np.ndarray):
        def __isub__(self, other):
            raise RuntimeError

        def __add__(self, other):
            raise RuntimeError

    data = np.arange(-10, 10, 1, dtype=float)
    data.shape = (10, 2)
    mydata = data.view(MyArray)

    for norm in [mcolors.Normalize(), mcolors.LogNorm(),
                 mcolors.SymLogNorm(3, vmax=5, linscale=1),
                 mcolors.Normalize(vmin=mydata.min(), vmax=mydata.max()),
                 mcolors.SymLogNorm(3, vmin=mydata.min(), vmax=mydata.max()),
                 mcolors.PowerNorm(1)]:
        assert_array_equal(norm(mydata), norm(data))
        fig, ax = plt.subplots()
        ax.imshow(mydata, norm=norm)
        fig.canvas.draw()
        assert len(recwarn) == 0
        recwarn.clear() 
Example #17
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_PowerNorm_translation_invariance():
    a = np.array([0, 1/2, 1], dtype=float)
    expected = [0, 1/8, 1]
    pnorm = mcolors.PowerNorm(vmin=0, vmax=1, gamma=3)
    assert_array_almost_equal(pnorm(a), expected)
    pnorm = mcolors.PowerNorm(vmin=-2, vmax=-1, gamma=3)
    assert_array_almost_equal(pnorm(a - 2), expected) 
Example #18
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_PowerNorm():
    a = np.array([0, 0.5, 1, 1.5], dtype=float)
    pnorm = mcolors.PowerNorm(1)
    norm = mcolors.Normalize()
    assert_array_almost_equal(norm(a), pnorm(a))

    a = np.array([-0.5, 0, 2, 4, 8], dtype=float)
    expected = [0, 0, 1/16, 1/4, 1]
    pnorm = mcolors.PowerNorm(2, vmin=0, vmax=8)
    assert_array_almost_equal(pnorm(a), expected)
    assert pnorm(a[0]) == expected[0]
    assert pnorm(a[2]) == expected[2]
    assert_array_almost_equal(a[1:], pnorm.inverse(pnorm(a))[1:])

    # Clip = True
    a = np.array([-0.5, 0, 1, 8, 16], dtype=float)
    expected = [0, 0, 0, 1, 1]
    pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=True)
    assert_array_almost_equal(pnorm(a), expected)
    assert pnorm(a[0]) == expected[0]
    assert pnorm(a[-1]) == expected[-1]

    # Clip = True at call time
    a = np.array([-0.5, 0, 1, 8, 16], dtype=float)
    expected = [0, 0, 0, 1, 1]
    pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=False)
    assert_array_almost_equal(pnorm(a, clip=True), expected)
    assert pnorm(a[0], clip=True) == expected[0]
    assert pnorm(a[-1], clip=True) == expected[-1] 
Example #19
Source File: test_colors.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_PowerNorm():
    a = np.array([0, 0.5, 1, 1.5], dtype=np.float)
    pnorm = mcolors.PowerNorm(1)
    norm = mcolors.Normalize()
    assert_array_almost_equal(norm(a), pnorm(a))

    a = np.array([-0.5, 0, 2, 4, 8], dtype=np.float)
    expected = [0, 0, 1/16, 1/4, 1]
    pnorm = mcolors.PowerNorm(2, vmin=0, vmax=8)
    assert_array_almost_equal(pnorm(a), expected)
    assert_equal(pnorm(a[0]), expected[0])
    assert_equal(pnorm(a[2]), expected[2])
    assert_array_almost_equal(a[1:], pnorm.inverse(pnorm(a))[1:])

    # Clip = True
    a = np.array([-0.5, 0, 1, 8, 16], dtype=np.float)
    expected = [0, 0, 0, 1, 1]
    pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=True)
    assert_array_almost_equal(pnorm(a), expected)
    assert_equal(pnorm(a[0]), expected[0])
    assert_equal(pnorm(a[-1]), expected[-1])

    # Clip = True at call time
    a = np.array([-0.5, 0, 1, 8, 16], dtype=np.float)
    expected = [0, 0, 0, 1, 1]
    pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=False)
    assert_array_almost_equal(pnorm(a, clip=True), expected)
    assert_equal(pnorm(a[0], clip=True), expected[0])
    assert_equal(pnorm(a[-1], clip=True), expected[-1]) 
Example #20
Source File: drapeplot.py    From LSDMappingTools with MIT License 4 votes vote down vote up
def make_drape_plot(self):
        """Creates a matplotlib Axes object with the drape map."""
        
        # but what if fig XOR ax is None??
#        if fig is None and ax is None:
#            self.fig, self.ax = plt.subplots()
#        else:
#            self.fig=fig, self.ax=ax

        
        
        # Plot the background
        self.im_background = self.ax.imshow(self.Background.Hillshade,
                                 self.Background.colourmap,
                                 extent=self.Background.extents,
                                 interpolation="nearest", vmax=450)
        self._num_drapes += 1
        self._drape_list.append(self.im_background)
        
        if self._show_background_colourbar:
            # Plot the background image colour bar
            self._generic_colourbar_plotter(self.im_background, "Elevation (m)")
        
        # Plot the drape (overlay data) on top.
        # Should be separate function really...
        if not self.HideDrape:
            self.im = self.ax.imshow(self.Drape._RasterArray,
                                     self._drape_colourmap,
                                     extent=self.Drape.extents,
                                     interpolation="nearest",
                                     vmin=self._vmin, vmax=self._vmax,
                                     norm=self._colourbar_normalisation,
                                     alpha=self._drape_alpha
                                     )
                                     #norm=_mcolors.PowerNorm(gamma=0.2))
            
            self._drape_list.append(self.im)
            self._num_drapes += 1
            
            
            
            # Add the colourbar for the drape
            self._generic_colourbar_plotter(self.im, self._colourbar_label)
        
        # Add a title
        self._set_subplot_autolabel()
        self._set_axis_labels(self._xaxis_label, self._yaxis_label)
        
        
        #return self.fig, self.ax