Пример #1
0
    def __call__(self, x, pos=None):
        if self.percentage:
            x = (100.0 * x)
            if x > 99.9:
                s = '{:.2f}%'.format(x)
            elif x > 99:
                s = '{:.1f}%'.format(x)
            elif x >= 1:
                s = '{:.0f}%'.format(x)
            elif x >= 0.1:
                s = '{:.1f}%'.format(x)
            else:
                s = '{:.2f}%'.format(x)
            return s

        if 0.01 <= x <= 0.99:
            s = '{:.2f}'.format(x)
        elif x < 0.01:
            lx = np.floor(np.log10(x))
            if lx >= -3:
                s = '{:.3f}'.format(x)
            elif is_decade(x):
                s = '$10^{{{:.0f}}}$'.format(np.log10(x))
            else:
                s = '${:.3f}$'.format(x)
        else:  # x > 0.99
            lx = np.floor(np.log10(1 - x))
            if lx >= -3:
                s = '{:.3f}'.format(x)
            else:
                s = '{:.4f}$'.format(x)
        return s
    def view_limits(self, vmin, vmax):
        'Try to choose the view limits intelligently'
        b = self._base
        
        if vmax < vmin:
            vmin, vmax = vmax, vmin

        if self.axis.axes.name == 'polar':
            vmax = math.ceil(math.log(vmax - self.zero) / math.log(b))
            vmin = b ** (vmax - self.numdecs)
            return vmin, vmax

        minpos = self.axis.get_minpos()

        if (self.sign > 0.0) :
            if vmax <= self.zero or not np.isfinite(minpos):
                raise ValueError(
                    "Data has no positive values, and therefore can not be "
                    "log-scaled.")
        else:
            if vmin >= self.zero or not np.isfinite(minpos):
                raise ValueError(
                    "Data has no positive values, and therefore can not be "
                    "log-scaled.")
            
        if not is_decade((vmin - self.zero) * self.sign, self._base):
            if self.sign > 0.0:
                vmin = decade_down((vmin - self.zero) * self.sign, self._base) + self.zero
            else:
                vmin = decade_up((vmin - self.zero) * self.sign, self._base) * self.sign + self.zero
        if not is_decade((vmax - self.zero) * self.sign, self._base):
            if self.sign > 0.0:
                vmax = decade_up((vmax - self.zero) * self.sign, self._base) + self.zero
            else:
                vmax = decade_down((vmax - self.zero) * self.sign, self._base) * self.sign + self.zero
        if vmin == vmax:
            if (self.sign > 0.0):
                vmin = decade_down((vmin - self.zero) * self.sign, self._base) + self.zero
                vmax = decade_up((vmax - self.zero) * self.sign, self._base) + self.zero
            else:
                vmin = decade_up((vmin - self.zero) * self.sign, self._base) * self.sign + self.zero
                vmax = decade_down((vmax - self.zero) * self.sign, self._base) * self.sign + self.zero
            
        result = mtransforms.nonsingular(vmin, vmax)
        return result
Пример #3
0
 def __call__(self, x, pos=None):
     s = ''
     if 0.01 <= x <= 0.99:
         if x in [.01, 0.1, 0.5, 0.9, 0.99]:
             s = '{:.2f}'.format(x)
     elif 0.001 <= x <= 0.999:
         if x in [.001, 0.999]:
             s = '{:.3f}'.format(x)
     elif 0.0001 <= x <= 0.9999:
         if x in [.0001, 0.9999]:
             s = '{:.4f}'.format(x)
     elif 0.00001 <= x <= 0.99999:
         if x in [.00001, 0.99999]:
             s = '{:.5f}'.format(x)
     elif x < 0.00001:
         if mticker.is_decade(x):
             s = '$10^{%.0f}$' % np.log10(x)
     elif x > 0.99999:
         if mticker.is_decade(1 - x):
             s = '$1-10^{%.0f}$' % np.log10(1 - x)
     return s
Пример #4
0
 def __call__(self, x, pos=None):
     """Format the minor tick label if less than 2 visible major ticks.
     """
     viewlim = self.axis.get_view_interval()
     loglim = numpy.log10(viewlim)
     majticks = numpy.arange(ceil(loglim[0]), floor(ceil(loglim[1])),
                             dtype=int)
     nticks = majticks.size
     halfdecade = nticks == 1 and modf(loglim[0])[0] < 0.7
     # if already two major ticks, don't need minor labels
     if nticks >= 2 or (halfdecade and not is_decade(x * 2, self._base)):
         return ''
     return super(MinorLogFormatterMathtext, self).__call__(x, pos=pos)
Пример #5
0
 def __call__(self, x, pos=None):
     """Format the minor tick label if less than 2 visible major ticks.
     """
     viewlim = self.axis.get_view_interval()
     loglim = numpy.log10(viewlim)
     majticks = numpy.arange(ceil(loglim[0]), floor(ceil(loglim[1])), dtype=int)
     nticks = majticks.size
     halfdecade = nticks == 1 and modf(loglim[0])[0] < 0.7
     # if already two major ticks, don't need minor labels
     if nticks >= 2 or (halfdecade and not is_decade(x * 2, self._base)):
         return ''
     else:
         return super(MinorLogFormatterMathtext, self).__call__(x, pos=pos)
Пример #6
0
 def __call__(self, x, pos=None):
     'Return the format for tick val x at position pos'
     vmin, vmax = self.axis.get_view_interval()
     d = abs(vmax - vmin)
     b = self._base
     # only label the decades
     sgn = numerix.sign(x)
     x = abs(x)
     x += self.threshold
     isDecade = ticker.is_decade(x)
     bx = b**x
     sgnbx = sgn * bx
     if not isDecade and self.labelOnlyBase: s = ''
     elif x > 4: s = '%+1.0e' % sgnbx
     elif x < 0: s = '%+1.0e' % sgnbx
     else: s = self.pprint_val(sgnbx, d)
     return s
 def __call__(self, x, pos=None):
     'Return the format for tick val x at position pos'
     vmin, vmax = self.axis.get_view_interval()
     d = abs(vmax - vmin)
     b=self._base
     # only label the decades
     sgn = numerix.sign(x)
     x = abs(x)
     x += self.threshold
     isDecade = ticker.is_decade(x)
     bx = b**x
     sgnbx = sgn * bx
     if not isDecade and self.labelOnlyBase: s = ''
     elif x > 4: s= '%+1.0e' % sgnbx
     elif x < 0: s =  '%+1.0e' % sgnbx
     else        : s =  self.pprint_val(sgnbx, d)
     return s
Пример #8
0
 def __call__(self, x, pos=None):
     if is_decade(x, self._base):
         return super(MinorLogFormatterMathtext, self).__call__(x, pos=pos)
     else:
         return super(CombinedLogFormatterMathtext, self).__call__(x,
                                                                   pos=pos)
Пример #9
0
 def __call__(self, x, pos=None):
     if is_decade(x, self._base):
         # pylint: disable=bad-super-call
         return super(MinorLogFormatterMathtext, self).__call__(x, pos=pos)
     return super(CombinedLogFormatterMathtext, self).__call__(x, pos=pos)
Пример #10
0
Файл: log.py Проект: bfarr/gwpy
 def __call__(self, x, pos=None):
     if is_decade(x, self._base):
         return super(MinorLogFormatterMathtext, self).__call__(x, pos=pos)
     else:
         return super(CombinedLogFormatterMathtext, self).__call__(x,
                                                                   pos=pos)
Пример #11
0
 def __call__(self, x, pos=None):
     if is_decade(x, self._base):
         # pylint: disable=bad-super-call
         return super(MinorLogFormatterMathtext, self).__call__(x, pos=pos)
     return super(CombinedLogFormatterMathtext, self).__call__(x, pos=pos)
Пример #12
0
    def add_colorbar(self, mappable=None, ax=None, location='right',
                     width=0.2, pad=0.1, log=None, label="", clim=None,
                     clip=None, visible=True, axes_class=axes.Axes, **kwargs):
        """Add a colorbar to the current `Axes`

        Parameters
        ----------
        mappable : matplotlib data collection
            collection against which to map the colouring
        ax : :class:`~matplotlib.axes.Axes`
            axes from which to steal space for the colour-bar
        location : `str`, optional, default: 'right'
            position of the colorbar
        width : `float`, optional default: 0.2
            width of the colorbar as a fraction of the axes
        pad : `float`, optional, default: 0.1
            gap between the axes and the colorbar as a fraction of the axes
        log : `bool`, optional, default: `False`
            display the colorbar with a logarithmic scale
        label : `str`, optional, default: '' (no label)
            label for the colorbar
        clim : pair of floats, optional
            (lower, upper) limits for the colorbar scale, values outside
            of these limits will be clipped to the edges
        visible : `bool`, optional, default: `True`
            make the colobar visible on the figure, this is useful to
            make two plots, each with and without a colorbar, but
            guarantee that the axes will be the same size
        **kwargs
            other keyword arguments to be passed to the
            :meth:`~matplotlib.figure.Figure.colorbar` generator

        Returns
        -------
        Colorbar
            the :class:`~matplotlib.colorbar.Colorbar` added to this plot
        """
        # find default layer
        if mappable is None and ax is not None and len(ax.collections):
            mappable = ax.collections[-1]
        elif mappable is None and ax is not None and len(ax.images):
            mappable = ax.images[-1]
        elif (visible is False and mappable is None and
              ax is not None and len(ax.lines)):
            mappable = ax.lines[-1]
        elif mappable is None and ax is None:
            for ax in self.axes[::-1]:
                if hasattr(ax, 'collections') and len(ax.collections):
                    mappable = ax.collections[-1]
                    break
                elif hasattr(ax, 'images') and len(ax.images):
                    mappable = ax.images[-1]
                    break
                elif visible is False and len(ax.lines):
                    mappable = ax.lines[-1]
                    break
        if not mappable:
            raise ValueError("Cannot determine mappable layer for this "
                             "colorbar")

        # find default axes
        if not ax:
            ax = mappable.axes

        # get new colour axis
        divider = make_axes_locatable(ax)
        if location == 'right':
            cax = divider.new_horizontal(size=width, pad=pad,
                                         axes_class=axes_class)
        elif location == 'top':
            cax = divider.new_vertical(size=width, pad=pad,
                                       axes_class=axes_class)
        else:
            raise ValueError("'left' and 'bottom' colorbars have not "
                             "been implemented")
        if visible:
            divider._fig.add_axes(cax)
        else:
            return

        # set limits
        if not clim:
            clim = mappable.get_clim()
        if log is None:
            log = isinstance(mappable, mcolors.LogNorm)
        if log and clim[0] <= 0.0:
            cdata = mappable.get_array()
            try:
                clim = (cdata[cdata>0.0].min(), clim[1])
            except ValueError:
                pass
        mappable.set_clim(clim)

        # set tick format (including sub-ticks for log scales)
        if pyplot.rcParams["text.usetex"]:
            if log and abs(float.__sub__(*numpy.log10(clim))) >= 2:
                func = lambda x,pos: (mticker.is_decade(x) and
                                  '$%s$' % tex.float_to_latex(x, '%.4g') or ' ')
            else:
                func = lambda x,pos: '$%s$' % tex.float_to_latex(x, '% .4g')
            kwargs.setdefault('format', mticker.FuncFormatter(func))

        # set log scale
        norm = mappable.norm
        if clip is None:
            clip = norm.clip
        if log and not isinstance(norm, mcolors.LogNorm):
            mappable.set_norm(mcolors.LogNorm(*mappable.get_clim()))
        else:
            mappable.set_norm(mcolors.Normalize(*mappable.get_clim()))
        mappable.norm.clip = clip

        # set tick locator
        if log:
            kwargs.setdefault('ticks',
                              mticker.LogLocator(subs=numpy.arange(1,11)))

        # make colour bar
        colorbar = self.colorbar(mappable, cax=cax, **kwargs)
        self.coloraxes.append(cax)

        # set label
        if label:
            colorbar.set_label(label)
        colorbar.draw_all()

        return colorbar