Python matplotlib.colors.SymLogNorm() Examples

The following are 30 code examples of matplotlib.colors.SymLogNorm(). 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: test_colors.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def test_SymLogNorm():
    """
    Test SymLogNorm behavior
    """
    norm = mcolors.SymLogNorm(3, vmax=5, linscale=1.2)
    vals = np.array([-30, -1, 2, 6], dtype=float)
    normed_vals = norm(vals)
    expected = [0., 0.53980074, 0.826991, 1.02758204]
    assert_array_almost_equal(normed_vals, expected)
    _inverse_tester(norm, vals)
    _scalar_tester(norm, vals)
    _mask_tester(norm, vals)

    # Ensure that specifying vmin returns the same result as above
    norm = mcolors.SymLogNorm(3, vmin=-30, vmax=5, linscale=1.2)
    normed_vals = norm(vals)
    assert_array_almost_equal(normed_vals, expected) 
Example #2
Source File: test_colors.py    From neural-network-animation with MIT License 6 votes vote down vote up
def test_SymLogNorm():
    """
    Test SymLogNorm behavior
    """
    norm = mcolors.SymLogNorm(3, vmax=5, linscale=1.2)
    vals = np.array([-30, -1, 2, 6], dtype=np.float)
    normed_vals = norm(vals)
    expected = [0., 0.53980074, 0.826991, 1.02758204]
    assert_array_almost_equal(normed_vals, expected)
    _inverse_tester(norm, vals)
    _scalar_tester(norm, vals)
    _mask_tester(norm, vals)

    # Ensure that specifying vmin returns the same result as above
    norm = mcolors.SymLogNorm(3, vmin=-30, vmax=5, linscale=1.2)
    normed_vals = norm(vals)
    assert_array_almost_equal(normed_vals, expected) 
Example #3
Source File: colorbar.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _get_ticker_locator_formatter(self):
        """
        This code looks at the norm being used by the colorbar
        and decides what locator and formatter to use.  If ``locator`` has
        already been set by hand, it just returns
        ``self.locator, self.formatter``.
        """
        locator = self.locator
        formatter = self.formatter
        if locator is None:
            if self.boundaries is None:
                if isinstance(self.norm, colors.NoNorm):
                    nv = len(self._values)
                    base = 1 + int(nv / 10)
                    locator = ticker.IndexLocator(base=base, offset=0)
                elif isinstance(self.norm, colors.BoundaryNorm):
                    b = self.norm.boundaries
                    locator = ticker.FixedLocator(b, nbins=10)
                elif isinstance(self.norm, colors.LogNorm):
                    locator = _ColorbarLogLocator(self)
                elif isinstance(self.norm, colors.SymLogNorm):
                    # The subs setting here should be replaced
                    # by logic in the locator.
                    locator = ticker.SymmetricalLogLocator(
                                      subs=np.arange(1, 10),
                                      linthresh=self.norm.linthresh,
                                      base=10)
                else:
                    if mpl.rcParams['_internal.classic_mode']:
                        locator = ticker.MaxNLocator()
                    else:
                        locator = _ColorbarAutoLocator(self)
            else:
                b = self._boundaries[self._inside]
                locator = ticker.FixedLocator(b, nbins=10)
        _log.debug('locator: %r', locator)
        return locator, formatter 
Example #4
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_SymLogNorm():
    """
    Test SymLogNorm behavior
    """
    norm = mcolors.SymLogNorm(3, vmax=5, linscale=1.2)
    vals = np.array([-30, -1, 2, 6], dtype=float)
    normed_vals = norm(vals)
    expected = [0., 0.53980074, 0.826991, 1.02758204]
    assert_array_almost_equal(normed_vals, expected)
    _inverse_tester(norm, vals)
    _scalar_tester(norm, vals)
    _mask_tester(norm, vals)

    # Ensure that specifying vmin returns the same result as above
    norm = mcolors.SymLogNorm(3, vmin=-30, vmax=5, linscale=1.2)
    normed_vals = norm(vals)
    assert_array_almost_equal(normed_vals, expected) 
Example #5
Source File: test_colors.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def test_SymLogNorm():
    """
    Test SymLogNorm behavior
    """
    norm = mcolors.SymLogNorm(3, vmax=5, linscale=1.2)
    vals = np.array([-30, -1, 2, 6], dtype=float)
    normed_vals = norm(vals)
    expected = [0., 0.53980074, 0.826991, 1.02758204]
    assert_array_almost_equal(normed_vals, expected)
    _inverse_tester(norm, vals)
    _scalar_tester(norm, vals)
    _mask_tester(norm, vals)

    # Ensure that specifying vmin returns the same result as above
    norm = mcolors.SymLogNorm(3, vmin=-30, vmax=5, linscale=1.2)
    normed_vals = norm(vals)
    assert_array_almost_equal(normed_vals, expected) 
Example #6
Source File: mpl_camera.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def norm(self, norm):

        if norm == "lin":
            self.pixels.norm = Normalize()
        elif norm == "log":
            self.pixels.norm = LogNorm()
            self.pixels.autoscale()  # this is to handle matplotlib bug #5424
        elif norm == "symlog":
            self.pixels.norm = SymLogNorm(linthresh=1.0)
            self.pixels.autoscale()
        elif isinstance(norm, Normalize):
            self.pixels.norm = norm
        else:
            raise ValueError(
                "Unsupported norm: '{}', options are 'lin',"
                "'log','symlog', or a matplotlib Normalize object".format(norm)
            )

        self.update(force=True)
        self.pixels.autoscale() 
Example #7
Source File: test_colors.py    From ImageFusion with MIT License 6 votes vote down vote up
def test_SymLogNorm():
    """
    Test SymLogNorm behavior
    """
    norm = mcolors.SymLogNorm(3, vmax=5, linscale=1.2)
    vals = np.array([-30, -1, 2, 6], dtype=np.float)
    normed_vals = norm(vals)
    expected = [0., 0.53980074, 0.826991, 1.02758204]
    assert_array_almost_equal(normed_vals, expected)
    _inverse_tester(norm, vals)
    _scalar_tester(norm, vals)
    _mask_tester(norm, vals)

    # Ensure that specifying vmin returns the same result as above
    norm = mcolors.SymLogNorm(3, vmin=-30, vmax=5, linscale=1.2)
    normed_vals = norm(vals)
    assert_array_almost_equal(normed_vals, expected) 
Example #8
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 #9
Source File: audio.py    From Self-Supervised-Speech-Pretraining-and-Representation-Learning with MIT License 5 votes vote down vote up
def plot_embedding(spec, path):
    spec = spec.transpose(1, 0) # (seq_len, feature_dim) -> (feature_dim, seq_len)
    plt.gcf().clear()
    plt.figure(figsize=(12, 3))
    plt.pcolormesh(spec, norm=SymLogNorm(linthresh=1e-3))
    plt.colorbar()
    plt.tight_layout()
    plt.savefig(path, dpi=300, format="png")
    plt.close() 
Example #10
Source File: test_colors.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_SymLogNorm_colorbar():
    """
    Test un-called SymLogNorm in a colorbar.
    """
    norm = mcolors.SymLogNorm(0.1, vmin=-1, vmax=1, linscale=1)
    fig = plt.figure()
    cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm)
    plt.close(fig) 
Example #11
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 #12
Source File: test_colors.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_SymLogNorm_single_zero():
    """
    Test SymLogNorm to ensure it is not adding sub-ticks to zero label
    """
    fig = plt.figure()
    norm = mcolors.SymLogNorm(1e-5, vmin=-1, vmax=1)
    cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm)
    ticks = cbar.get_ticks()
    assert sum(ticks == 0) == 1
    plt.close(fig) 
Example #13
Source File: test_colors.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_SymLogNorm_colorbar():
    """
    Test un-called SymLogNorm in a colorbar.
    """
    norm = mcolors.SymLogNorm(0.1, vmin=-1, vmax=1, linscale=1)
    fig = plt.figure()
    cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm)
    plt.close(fig) 
Example #14
Source File: colorbar.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def _get_ticker_locator_formatter(self):
        """
        This code looks at the norm being used by the colorbar
        and decides what locator and formatter to use.  If ``locator`` has
        already been set by hand, it just returns
        ``self.locator, self.formatter``.
        """
        locator = self.locator
        formatter = self.formatter
        if locator is None:
            if self.boundaries is None:
                if isinstance(self.norm, colors.NoNorm):
                    nv = len(self._values)
                    base = 1 + int(nv / 10)
                    locator = ticker.IndexLocator(base=base, offset=0)
                elif isinstance(self.norm, colors.BoundaryNorm):
                    b = self.norm.boundaries
                    locator = ticker.FixedLocator(b, nbins=10)
                elif isinstance(self.norm, colors.LogNorm):
                    locator = _ColorbarLogLocator(self)
                elif isinstance(self.norm, colors.SymLogNorm):
                    # The subs setting here should be replaced
                    # by logic in the locator.
                    locator = ticker.SymmetricalLogLocator(
                                      subs=np.arange(1, 10),
                                      linthresh=self.norm.linthresh,
                                      base=10)
                else:
                    if mpl.rcParams['_internal.classic_mode']:
                        locator = ticker.MaxNLocator()
                    else:
                        locator = _ColorbarAutoLocator(self)
            else:
                b = self._boundaries[self._inside]
                locator = ticker.FixedLocator(b, nbins=10)
        _log.debug('locator: %r', locator)
        return locator, formatter 
Example #15
Source File: hiccompare.py    From CoolBox with GNU General Public License v3.0 5 votes vote down vote up
def __plot_matrix(self, genome_range):
        start, end = genome_range.start, genome_range.end
        ax = self.ax
        arr = self.matrix
        if isinstance(self.properties['color'], str):
            cmap = plt.get_cmap(self.properties['color'])
        else:
            cmap = self.properties['color']
        cmap.set_bad("white")
        cmap.set_under("white")
        c_min_1, c_max_1 = self.hic1.matrix_val_range
        c_min_2, c_max_2 = self.hic2.matrix_val_range

        self.small_value = ( abs(c_min_1) + abs(c_min_2) ) / 2

        if self.properties['norm'] == 'log':
            a_ = np.log10(c_max_1)
            b_ = np.log10(c_max_2)
            c_ = np.log10(self.small_value)
            ra_ = abs(c_ - a_) + 0.7
            rb_ = abs(c_ - b_) + 0.7

            midpoint = (ra_ / (ra_ + rb_))
        else:
            midpoint = (abs(c_max_2) / (abs(c_max_1) + abs(c_max_2)))

        cmap = shiftedColorMap(cmap, midpoint=midpoint)

        img = ax.matshow(arr, cmap=cmap,
                         extent=(start, end, end, start),
                         aspect='auto')

        if self.properties['norm'] == 'log':
            img.set_norm(colors.SymLogNorm(linthresh=self.small_value, linscale=1, vmin=-c_max_1, vmax=c_max_2))
        else:
            img.set_norm(colors.Normalize(vmin=-c_max_1, vmax=c_max_2))

        return img 
Example #16
Source File: planners_visualization.py    From rl-agents with MIT License 5 votes vote down vote up
def show_state_map(title, agent_name, values, state_limits, v_max=None):
    fig, ax = plt.subplots()
    img = ax.imshow(values.T,
                    extent=(-state_limits, state_limits, -state_limits, state_limits),
                    norm=colors.SymLogNorm(linthresh=1, linscale=1, vmax=v_max),
                    cmap=plt.cm.coolwarm)
    fig.colorbar(img, ax=ax)
    plt.grid(False)
    plt.title(rename(agent_name))
    plt.savefig(out / "{}_{}.pdf".format(title, agent_name))
    plt.show() 
Example #17
Source File: drapeplot.py    From LSDMappingTools with MIT License 5 votes vote down vote up
def set_colourbar_norm_type(self, colourbar_norm_type):
        if colourbar_norm_type == "SymLogNorm":
            norm = _mcolors.SymLogNorm(linthresh=0.3, vmin=self._vmin, vmax=self._vmax)
        elif colourbar_norm_type is None:
            norm = None
        else:
            raise NotImplementedError("That type of normalisation is not coded in yet..")
            norm = None
        
        return norm 
Example #18
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 #19
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 #20
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_SymLogNorm_single_zero():
    """
    Test SymLogNorm to ensure it is not adding sub-ticks to zero label
    """
    fig = plt.figure()
    norm = mcolors.SymLogNorm(1e-5, vmin=-1, vmax=1)
    cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm)
    ticks = cbar.get_ticks()
    assert sum(ticks == 0) == 1
    plt.close(fig) 
Example #21
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_SymLogNorm_colorbar():
    """
    Test un-called SymLogNorm in a colorbar.
    """
    norm = mcolors.SymLogNorm(0.1, vmin=-1, vmax=1, linscale=1)
    fig = plt.figure()
    cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm)
    plt.close(fig) 
Example #22
Source File: colorbar.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_ticker_locator_formatter(self):
        """
        This code looks at the norm being used by the colorbar
        and decides what locator and formatter to use.  If ``locator`` has
        already been set by hand, it just returns
        ``self.locator, self.formatter``.
        """
        locator = self.locator
        formatter = self.formatter
        if locator is None:
            if self.boundaries is None:
                if isinstance(self.norm, colors.NoNorm):
                    nv = len(self._values)
                    base = 1 + int(nv / 10)
                    locator = ticker.IndexLocator(base=base, offset=0)
                elif isinstance(self.norm, colors.BoundaryNorm):
                    b = self.norm.boundaries
                    locator = ticker.FixedLocator(b, nbins=10)
                elif isinstance(self.norm, colors.LogNorm):
                    locator = _ColorbarLogLocator(self)
                elif isinstance(self.norm, colors.SymLogNorm):
                    # The subs setting here should be replaced
                    # by logic in the locator.
                    locator = ticker.SymmetricalLogLocator(
                                      subs=np.arange(1, 10),
                                      linthresh=self.norm.linthresh,
                                      base=10)
                else:
                    if mpl.rcParams['_internal.classic_mode']:
                        locator = ticker.MaxNLocator()
                    else:
                        locator = _ColorbarAutoLocator(self)
            else:
                b = self._boundaries[self._inside]
                locator = ticker.FixedLocator(b, nbins=10)
        _log.debug('locator: %r', locator)
        return locator, formatter 
Example #23
Source File: test_colors.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_SymLogNorm_single_zero():
    """
    Test SymLogNorm to ensure it is not adding sub-ticks to zero label
    """
    fig = plt.figure()
    norm = mcolors.SymLogNorm(1e-5, vmin=-1, vmax=1)
    cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm)
    ticks = cbar.get_ticks()
    assert sum(ticks == 0) == 1
    plt.close(fig) 
Example #24
Source File: scatter.py    From nata with MIT License 5 votes vote down vote up
def build_canvas(self):
        # get plot axes and data
        x = self.data.data[0]
        y = self.data.data[1]

        # build color map norm
        if self.cb_scale == "log":
            self.cb_norm = clr.LogNorm(vmin=self.vmin, vmax=self.vmax)
        elif self.cb_scale == "symlog":
            self.cb_norm = clr.SymLogNorm(
                vmin=self.vmin,
                vmax=self.vmax,
                linthresh=self.cb_linthresh,
                base=10,
            )
        else:
            self.cb_norm = clr.Normalize(vmin=self.vmin, vmax=self.vmax)

        # build plot
        self.h = self.axes.ax.scatter(
            x,
            y,
            s=self.s,
            c=self.c,
            marker=self.marker,
            alpha=self.alpha,
            label=self.label,
            cmap=self.cb_map,
            norm=self.cb_norm
            # antialiased=self.antialiased,
        )

        if self.has_cb:
            self.axes.init_colorbar(plot=self) 
Example #25
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 #26
Source File: response.py    From threeML with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plot_matrix(self):

        fig, ax = plt.subplots()

        idx_mc = 0
        idx_eb = 0

        # Some times the lower edges may be zero, so we skip them

        if self._mc_energies[0] == 0:
            idx_mc = 1

        if self._ebounds[0] == 0:
            idx_eb = 1

        # ax.imshow(image[idx_eb:, idx_mc:], extent=(self._ebounds[idx_eb],
        #                                            self._ebounds[-1],
        #                                            self._mc_energies[idx_mc],
        #                                            self._mc_energies[-1]),
        #           aspect='equal',
        #           cmap=cm.BrBG_r,
        #           origin='lower',
        #           norm=SymLogNorm(1.0, 1.0, vmin=self._matrix.min(), vmax=self._matrix.max()))

        # Find minimum non-zero element
        vmin = self._matrix[self._matrix > 0].min()

        cmap = copy.deepcopy(cm.ocean)

        cmap.set_under("gray")

        mappable = ax.pcolormesh(
            self._mc_energies[idx_mc:],
            self._ebounds[idx_eb:],
            self._matrix,
            cmap=cmap,
            norm=SymLogNorm(1.0, 1.0, vmin=vmin, vmax=self._matrix.max()),
        )

        ax.set_xscale("log")
        ax.set_yscale("log")

        fig.colorbar(mappable, label="cm$^{2}$")

        # if show_energy is not None:
        #    ener_val = Quantity(show_energy).to(self.reco_energy.unit).value
        #    ax.hlines(ener_val, 0, 200200, linestyles='dashed')

        ax.set_xlabel("True energy (keV)")
        ax.set_ylabel("Reco energy (keV)")

        return fig 
Example #27
Source File: colorbar.py    From twitter-stock-recommendation with MIT License 4 votes vote down vote up
def _ticker(self):
        '''
        Return the sequence of ticks (colorbar data locations),
        ticklabels (strings), and the corresponding offset string.
        '''
        locator = self.locator
        formatter = self.formatter
        if locator is None:
            if self.boundaries is None:
                if isinstance(self.norm, colors.NoNorm):
                    nv = len(self._values)
                    base = 1 + int(nv / 10)
                    locator = ticker.IndexLocator(base=base, offset=0)
                elif isinstance(self.norm, colors.BoundaryNorm):
                    b = self.norm.boundaries
                    locator = ticker.FixedLocator(b, nbins=10)
                elif isinstance(self.norm, colors.LogNorm):
                    locator = ticker.LogLocator(subs='all')
                elif isinstance(self.norm, colors.SymLogNorm):
                    # The subs setting here should be replaced
                    # by logic in the locator.
                    locator = ticker.SymmetricalLogLocator(
                                      subs=np.arange(1, 10),
                                      linthresh=self.norm.linthresh,
                                      base=10)
                else:
                    if mpl.rcParams['_internal.classic_mode']:
                        locator = ticker.MaxNLocator()
                    else:
                        locator = ticker.AutoLocator()
            else:
                b = self._boundaries[self._inside]
                locator = ticker.FixedLocator(b, nbins=10)
        if isinstance(self.norm, colors.NoNorm) and self.boundaries is None:
            intv = self._values[0], self._values[-1]
        else:
            intv = self.vmin, self.vmax
        locator.create_dummy_axis(minpos=intv[0])
        formatter.create_dummy_axis(minpos=intv[0])
        locator.set_view_interval(*intv)
        locator.set_data_interval(*intv)
        formatter.set_view_interval(*intv)
        formatter.set_data_interval(*intv)

        b = np.array(locator())
        if isinstance(locator, ticker.LogLocator):
            eps = 1e-10
            b = b[(b <= intv[1] * (1 + eps)) & (b >= intv[0] * (1 - eps))]
        else:
            eps = (intv[1] - intv[0]) * 1e-10
            b = b[(b <= intv[1] + eps) & (b >= intv[0] - eps)]
        self._tick_data_values = b
        ticks = self._locate(b)
        formatter.set_locs(b)
        ticklabels = [formatter(t, i) for i, t in enumerate(b)]
        offset_string = formatter.get_offset()
        return ticks, ticklabels, offset_string 
Example #28
Source File: colorbar.py    From CogAlg with MIT License 4 votes vote down vote up
def _get_ticker_locator_formatter(self):
        """
        This code looks at the norm being used by the colorbar
        and decides what locator and formatter to use.  If ``locator`` has
        already been set by hand, it just returns
        ``self.locator, self.formatter``.
        """
        locator = self.locator
        formatter = self.formatter
        if locator is None:
            if self.boundaries is None:
                if isinstance(self.norm, colors.NoNorm):
                    nv = len(self._values)
                    base = 1 + int(nv / 10)
                    locator = ticker.IndexLocator(base=base, offset=0)
                elif isinstance(self.norm, colors.BoundaryNorm):
                    b = self.norm.boundaries
                    locator = ticker.FixedLocator(b, nbins=10)
                elif isinstance(self.norm, colors.LogNorm):
                    locator = _ColorbarLogLocator(self)
                elif isinstance(self.norm, colors.SymLogNorm):
                    # The subs setting here should be replaced
                    # by logic in the locator.
                    locator = ticker.SymmetricalLogLocator(
                                      subs=np.arange(1, 10),
                                      linthresh=self.norm.linthresh,
                                      base=10)
                else:
                    if mpl.rcParams['_internal.classic_mode']:
                        locator = ticker.MaxNLocator()
                    else:
                        locator = _ColorbarAutoLocator(self)
            else:
                b = self._boundaries[self._inside]
                locator = ticker.FixedLocator(b, nbins=10)

        if formatter is None:
            if isinstance(self.norm, colors.LogNorm):
                formatter = ticker.LogFormatterSciNotation()
            elif isinstance(self.norm, colors.SymLogNorm):
                formatter = ticker.LogFormatterSciNotation(
                                        linthresh=self.norm.linthresh)
            else:
                formatter = ticker.ScalarFormatter()
        else:
            formatter = self.formatter

        self.locator = locator
        self.formatter = formatter
        _log.debug('locator: %r', locator)
        return locator, formatter 
Example #29
Source File: color.py    From nata with MIT License 4 votes vote down vote up
def build_canvas(self):
        # get plot extent and data
        extent = (
            self.data.axes[0].min,
            self.data.axes[0].max,
            self.data.axes[1].min,
            self.data.axes[1].max,
        )
        z = np.transpose(self.data.data)

        # build color map norm
        if self.cb_scale == "log":
            # convert values to positive numbers
            z = np.abs(z) + 1e-16

            # adjust min and max values
            # TODO: do this only if vmin was not init
            # self.vmin = np.min(z)

            # if self.vmax_auto:
            # self.vmax = np.max(z)

            # set color map norm
            self.cb_norm = clr.LogNorm(vmin=self.vmin, vmax=self.vmax)
        elif self.cb_scale == "symlog":
            # set color map norm
            self.cb_norm = clr.SymLogNorm(
                vmin=self.vmin,
                vmax=self.vmax,
                linthresh=self.cb_linthresh,
                base=10,
            )
        else:
            self.cb_norm = clr.Normalize(vmin=self.vmin, vmax=self.vmax)

        # build plot
        self.h = self.axes.ax.imshow(
            z,
            extent=extent,
            origin="lower",
            cmap=self.cb_map,
            norm=self.cb_norm,
            interpolation=self.interpolation,
        )

        self.axes.init_colorbar(plot=self) 
Example #30
Source File: colorbar.py    From Mastering-Elasticsearch-7.0 with MIT License 4 votes vote down vote up
def _get_ticker_locator_formatter(self):
        """
        This code looks at the norm being used by the colorbar
        and decides what locator and formatter to use.  If ``locator`` has
        already been set by hand, it just returns
        ``self.locator, self.formatter``.
        """
        locator = self.locator
        formatter = self.formatter
        if locator is None:
            if self.boundaries is None:
                if isinstance(self.norm, colors.NoNorm):
                    nv = len(self._values)
                    base = 1 + int(nv / 10)
                    locator = ticker.IndexLocator(base=base, offset=0)
                elif isinstance(self.norm, colors.BoundaryNorm):
                    b = self.norm.boundaries
                    locator = ticker.FixedLocator(b, nbins=10)
                elif isinstance(self.norm, colors.LogNorm):
                    locator = _ColorbarLogLocator(self)
                elif isinstance(self.norm, colors.SymLogNorm):
                    # The subs setting here should be replaced
                    # by logic in the locator.
                    locator = ticker.SymmetricalLogLocator(
                                      subs=np.arange(1, 10),
                                      linthresh=self.norm.linthresh,
                                      base=10)
                else:
                    if mpl.rcParams['_internal.classic_mode']:
                        locator = ticker.MaxNLocator()
                    else:
                        locator = _ColorbarAutoLocator(self)
            else:
                b = self._boundaries[self._inside]
                locator = ticker.FixedLocator(b, nbins=10)

        if formatter is None:
            if isinstance(self.norm, colors.LogNorm):
                formatter = ticker.LogFormatterSciNotation()
            elif isinstance(self.norm, colors.SymLogNorm):
                formatter = ticker.LogFormatterSciNotation(
                                        linthresh=self.norm.linthresh)
            else:
                formatter = ticker.ScalarFormatter()
        else:
            formatter = self.formatter

        self.locator = locator
        self.formatter = formatter
        _log.debug('locator: %r', locator)
        return locator, formatter