コード例 #1
0
ファイル: scale.py プロジェクト: dreamsxin/proplot
    def __init__(self, **kwargs):
        """
        Parameters
        ----------
        base : float, optional
            The base of the logarithm. Default is ``10``.
        linthresh : float, optional
            Defines the range ``(-linthresh, linthresh)``, within which the
            plot is linear.  This avoids having the plot go to infinity around
            zero. Defaults to 2.
        linscale : float, optional
            This allows the linear range ``(-linthresh, linthresh)`` to be
            stretched relative to the logarithmic range. Its value is the
            number of decades to use for each half of the linear range. For
            example, when `linscale` is ``1`` (the default), the space used
            for the positive and negative halves of the linear range will be
            equal to one decade in the logarithmic range.
        subs : sequence of int, optional
            Default *minor* tick locations are on these multiples of each power
            of the base. For example, ``subs=(1, 2, 5)`` draws ticks on 1, 2,
            5, 10, 20, 50, 100, 200, 500, etc. The default is
            ``subs=numpy.arange(1, 10)``.
        basex, basey, linthreshx, linthreshy, linscalex, linscaley, \
subsx, subsy
            Aliases for the above keywords. These used to be conditional
            on the *name* of the axis.
        """
        keys = ('base', 'linthresh', 'linscale', 'subs')
        super().__init__(**_parse_logscale_args(*keys, **kwargs))
        transform = self.get_transform()
        self._default_major_locator = mticker.SymmetricalLogLocator(transform)
        self._default_minor_locator = mticker.SymmetricalLogLocator(
            transform, self.subs)  # noqa: E501
コード例 #2
0
def plot(df, title, equation = 1):
    """
    Plot x1 vs x2 with contour lines.
    
    Input
        df:         dataframe with values to be plotted
        title:      chart title
        equation:       1: f(x1, x2) = x1^2 + 2.x2^2 - 2.x1.x2 - 2.x2
                        2: f(x1, x2) = r1(x)**2 + r2(x)**2 (method Levenberg-Marquardt)
                        3: f(x1, x2) = (x1 - 2)^4 + (x1 - 2.x2)^2

    """

    fig, ax = plt.subplots()

    # Compute contour lines
    delta_x1 = (1.5*max(df.x1) - min(df.x1)) / 1000
    delta_x2 = (1.5*max(df.x2) - min(df.x2)) / 1000

    d1 = (max(df.x1) - min(df.x1)) * 0.1
    d2 = (max(df.x2) - min(df.x2)) * 0.1
    x_1 = np.arange(min(df.x1) - d1, max(df.x1) + d1, delta_x1)
    x_2 = np.arange(min(df.x2) - d2, max(df.x2) + d2, delta_x2)
    x_1, x_2 = np.meshgrid(x_1, x_2)

    if equation == 1:
        f = x_1**2 + 2*x_2**2 - 2*x_1*x_2 - 2*x_2
        CS = ax.contour(x_1, x_2, f, locator = ticker.SymmetricalLogLocator(linthresh=1, base=10))
        locator = ticker.AutoLocator()

    elif equation == 3:
        f = (x_1 - 2)**4 + (x_1 - 2*x_2)**2
        locator = ticker.SymmetricalLogLocator(linthresh=0.1, base=2)

    else:
        print ("Only equations 1 and 3 are supported.")
        #return


    # Plot contour lines and labels
    CS = ax.contour(x_1, x_2, f, locator = locator)
    ax.clabel(CS, inline=1, fontsize=10)

    # Points
    x1 = df.x1
    x2 = df.x2

    ax.plot(x1, x2)
    ax.plot(x1, x2, 'ro')

    # Lables and title
    ax.set_title(title)
    ax.set_xlabel('x1')
    ax.set_ylabel('x2')

    plt.show()

    return
コード例 #3
0
ファイル: mcbin.py プロジェクト: xhRhapsody/momentsml
def make_symlog(ax, featbin, linthresh=2e-3, lim=1e-1):
    """
	Converts the y axis to a symlog scale with custom ticks, usually for the mcbin-plot from above
	"""

    ax.set_yscale('symlog', linthreshy=linthresh)
    ax.set_ylim([-lim, lim])
    ticks = np.concatenate([np.arange(-linthresh, linthresh, 1e-3)
                            ])  #, np.arange(lintresh, 1e-2, 9)])
    s = ax.yaxis._scale
    ax.yaxis.set_minor_locator(
        ticker.SymmetricalLogLocator(s,
                                     subs=[
                                         1., 2., 3., 4., 5., 6., 7., 8., 9.,
                                         -2., -3., -4., -5., -6., -7., -8., -9.
                                     ]))
    ticks = np.concatenate(
        [ticks, ax.yaxis.get_minor_locator().tick_values(-.1, .1)])
    ax.yaxis.set_minor_locator(ticker.FixedLocator(ticks))

    xlim = (featbin.low, featbin.high)
    ax.fill_between(xlim,
                    -linthresh,
                    linthresh,
                    alpha=0.2,
                    facecolor='darkgrey')
    ax.set_xlim(xlim)
コード例 #4
0
    def set_normalization(self, vmin, vmax, norm='linear'):

        if np.isclose(vmin, vmax): vmin, vmax = 1e-3, 1e+3

        if (norm.lower() == 'linear'):
            self.norm = colors.Normalize(vmin=vmin, vmax=vmax)
        elif (norm.lower() == 'logarithmic'):
            self.norm = colors.LogNorm(vmin=vmin, vmax=vmax)
        else:
            self.norm = colors.SymLogNorm(linthresh=0.1,
                                          linscale=0.9,
                                          base=10,
                                          vmin=vmin,
                                          vmax=vmax)

        self.s.set_norm(self.norm)

        if self.s.colorbar is not None:

            orientation = self.s.colorbar.orientation

            self.remove_colorbar()
            self.create_colorbar(orientation, norm)

            if (norm.lower() == 'symlog'):
                self.cb.locator = ticker.SymmetricalLogLocator(linthresh=0.1,
                                                               base=10)
                self.cb.update_ticks()
コード例 #5
0
    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
コード例 #6
0
ファイル: test_ticker.py プロジェクト: zimyk/matplotlib
 def test_set_params(self):
     """
     Create symmetrical log locator with default subs =[1.0] numticks = 15,
     and change it to something else.
     See if change was successful.
     Should not exception.
     """
     sym = mticker.SymmetricalLogLocator(base=10, linthresh=1)
     sym.set_params(subs=[2.0], numticks=8)
     assert sym._subs == [2.0]
     assert sym.numticks == 8
コード例 #7
0
ファイル: test_ticker.py プロジェクト: qianmoke/matplotlib
def test_SymmetricalLogLocator_set_params():
    """
    Create symmetrical log locator with default subs =[1.0] numticks = 15,
    and change it to something else.
    See if change was successful.
    Should not exception.
    """
    # since we only test for the params change. I will pass empty transform
    sym = mticker.SymmetricalLogLocator(None)
    sym.set_params(subs=[2.0], numticks=8)
    assert sym._subs == [2.0]
    assert sym.numticks == 8
コード例 #8
0
    def _clear(self):

        self._raw.set_major_locator(ticker.AutoLocator())
        self._raw.set_minor_locator(ticker.NullLocator())

        if self._scale == Scale.Log:
            self._raw.set_major_locator(ticker.LogLocator())
            self._raw.set_minor_locator(ticker.LogLocator(subs="auto"))
        elif self._scale == Scale.Logit:
            self._raw.set_major_locator(ticker.LogitLocator())
        elif self._scale == Scale.SymmetricLog:
            self._raw.set_major_locator(ticker.SymmetricalLogLocator())
コード例 #9
0
def plot_function():
    """
    Create a plot of the function f(x1, x2) with contour lines.
    """
    # Compute contour lines
    x_1 = np.arange(-10, 10, 0.5)
    x_2 = np.arange(-10, 10, 0.5)
    x_1, x_2 = np.meshgrid(x_1, x_2)

    for equation in [1, 3]:
        fig, ax = plt.subplots()

        # f(x) = x_1^2 + 2.x_2^2 - 2.x_1.x_2 - 2.x_2"
        if equation == 1:
            title = "F(x1, x2) Contour Map"
            f = x_1**2 + 2 * x_2**2 - 2 * x_1 * x_2 - 2 * x_2
            locator = ticker.AutoLocator()

        # Example 8.8.7 from "Nonlinear Programming"
        # f(x) = (x_1 - 2)^4 + (x_1 - 2.x_2)^2"
        else:
            title = "Example 8.8.7 Contour Map"
            f = (x_1 - 2)**4 + (x_1 - 2 * x_2)**2
            locator = ticker.SymmetricalLogLocator(linthresh=0.1, base=2)

        # Plot contour lines
        CS1 = ax.contourf(x_1,
                          x_2,
                          f,
                          locator=locator,
                          cmap=plt.get_cmap("plasma"))
        CS2 = ax.contour(x_1,
                         x_2,
                         f,
                         locator=locator,
                         colors='white',
                         linewidths=(0.5, ))

        # Color bar
        fig.colorbar(CS1, shrink=0.9)

        # Lables and title
        ax.set_title(title)
        ax.set_xlabel('x1')
        ax.set_ylabel('x2')

        plt.show()

        return
コード例 #10
0
ファイル: HybridHelper.py プロジェクト: npbarnes/hybridtools
def direct_plot(fig, ax, data, params, direction, depth=None, cax=None, time_coords=False, fontsize=None, mccomas=False, titlesize=25, labelsize=20, ticklabelsize=15, cbtitle='', skip_labeling=False, **kwargs):
    X, Y, dslice = plot_setup(ax, data, params, direction, depth, time_coords, fontsize=fontsize, mccomas=mccomas, titlesize=titlesize, labelsize=labelsize, ticklabelsize=ticklabelsize, skip_labeling=skip_labeling)

    mappable = ax.pcolormesh(X,Y,dslice.transpose(), **kwargs)

    fmt = plticker.FuncFormatter(scientific_format(digits=1))
    if cax != 'None':
        if cax == None:
            if 'SymLogNorm' in repr(kwargs['norm']):
                cb = fig.colorbar(mappable, ax=ax, shrink=0.7, ticks=plticker.SymmetricalLogLocator(linthresh=0.01, base=10))
            elif 'LogNorm' in repr(kwargs['norm']):
                cb = fig.colorbar(mappable, ax=ax, shrink=0.7, ticks=plticker.LogLocator())
            else:
                cb = fig.colorbar(mappable, ax=ax, shrink=0.7, format=fmt)
        else:
            cb = fig.colorbar(mappable, cax=cax, format=fmt)

        cb.ax.set_title(cbtitle, fontsize=ticklabelsize)

    return mappable, X, Y, dslice
コード例 #11
0
def minorticks_on(ax=None, which="both"):
    """Same as ax.minorticks_on, but takes a `which` parameter specifying `x`, `y` or `both`."""
    if ax == None:
        ax = plt.gca()
    if which == "both":
        axes = [ax.xaxis, ax.yaxis]
    elif which == "x":
        axes = [ax.xaxis]
    elif which == "y":
        axes = [ax.yaxis]
    for ax in axes:
        scale = ax.get_scale()
        if scale == 'log':
            s = ax._scale
            ax.set_minor_locator(mticker.LogLocator(s.base, s.subs))
        elif scale == 'symlog':
            s = ax._scale
            ax.set_minor_locator(
                mticker.SymmetricalLogLocator(s._transform, s.subs))
        else:
            ax.set_minor_locator(mticker.AutoMinorLocator())
コード例 #12
0
def fixedPotential_cBar(myFig,fraction="5%"):
    """
    This function fixes the colorbar of the potential colormap
    """
    
    ## I create another axis object for the colorbar 
    ## in order to use later tbe plt.tight_layout() function
    divider = make_axes_locatable(plt.gca())
    cax = divider.append_axes("right", fraction, pad="3%")
    cbar = myFig.colorbar(pColorMap, cax=cax)
    cbar.ax.set_ylabel('Potential (Volts)', fontsize=14)
    
    ## NOTE: the fact that symmetric log-scale colorbar tick labels 
    ## near zero don't appear correctly is a known pyplot issue
    ## see: https://matplotlib.org/users/colormapnorms.html
    ## here the large threshold partially alleviates the problem 
    ## but still we will do some modifications (remove minor ticks, fix v==0 tick) 
    
    ## fixing the ticks of the colorbar
    loc = ticker.SymmetricalLogLocator(linthresh=1E8,base=10)
    cbar.ax.yaxis.set_major_locator(loc)
    cbar.set_ticks(cbar.ax.yaxis.get_major_locator().tick_values(potential.min(), potential.max()))

    return
コード例 #13
0
    def plot(self, matrix, RHSvector, log='auto'):
        import tempfile
        import os

        if "print" in os.environ['FIPY_DISPLAY_MATRIX'].lower().split():
            print("-"*75)
            print(self.title)
            print("-"*75)
            print("L:")
            print(matrix)
            print("b:", RHSvector)

        (f, mtxName) = tempfile.mkstemp(suffix='.mtx')
        matrix.exportMmf(mtxName)
        mtx = mmio.mmread(mtxName)
        os.remove(mtxName)

        pyplot.ion()

        c = mtx.tocoo()
        y = c.row
        x = c.col
        z = c.data
        N = matrix._shape[0]

        b = RHSvector
        if numerix.shape(b) == ():
            b = numerix.zeros((N,), 'l')

        if len(z) == 0:
            y = numerix.zeros((1,), 'l')
            x = numerix.zeros((1,), 'l')
            z = numerix.zeros((1,), 'l')

        def signed_to_logs(v):
            return (numerix.where(v > 0, numerix.log10(v), numerix.nan),
                    numerix.where(v < 0, numerix.log10(-v), numerix.nan))

        def logs_to_signed(v, plus, minus):
            v = numerix.where(v > 0, plus, -minus)
            v = numerix.where(numerix.isnan(v), 0., v)

            return v

        zPlus, zMinus = signed_to_logs(z)
        bPlus, bMinus = signed_to_logs(b)

        logs = (zPlus, zMinus, bPlus, bMinus)

        log = ((log == True)
               or (log == 'auto'
                   and (numerix.nanmax(numerix.concatenate(logs))
                        - numerix.nanmin(numerix.concatenate(logs)) > 2)))

        if log:
            zMin = numerix.nanmin(numerix.concatenate(logs))
            zMax = numerix.nanmax(numerix.concatenate(logs))

            zMin -= 0.5

            numdec = numerix.floor(zMax) - numerix.ceil(zMin)
            if numdec < 0:
                zMax += 0.5

            for v in logs:
                v -= zMin

            zRange = zMax - zMin

            if zRange == 0:
                zRange = numerix.nanmax(zPlus) + 1

            z = logs_to_signed(z, zPlus, zMinus)
            b = logs_to_signed(b, bPlus, bMinus)

            fmt = None
            loc = ticker.SymmetricalLogLocator(linthresh=1, base=10)

        else:
            zRange = max(abs(numerix.concatenate((z, b))))

            if zRange == 0:
                zRange = 1

            fmt = None
            loc = None


        pyplot.ioff()

        fig = pyplot.figure(self.id)
        fig.clf()

        usetex = rcParams['text.usetex']
        rcParams['text.usetex'] = False

        cmap = cm.RdBu

        norm = Normalize(vmin=-zRange, vmax=zRange)

        x0 = self.margin
        L_ax = fig.add_axes([x0 / self.aspect, self.margin, self.L_width / self.aspect, self.L_width])
        L_ax.text(0.5, -0.1, "L",
                  transform=L_ax.transAxes, horizontalalignment='center', verticalalignment='baseline')

        x0 += self.L_width + self.buffer
        c_ax = fig.add_axes([x0 / self.aspect, self.margin, self.c_width / self.aspect, self.L_width])

        x0 += self.c_width + self.buffer
        b_ax = fig.add_axes([x0 / self.aspect, self.margin, self.b_width / self.aspect, self.L_width],
                            sharey=L_ax)
        b_ax.text(0.5, -0.1, "b",
                  transform=b_ax.transAxes, horizontalalignment='center', verticalalignment='baseline')



        def scatterRectangles(x, y, z, norm=None, cmap=None):
            patches = [Rectangle(numerix.array([X - 0.5, Y - 0.5]), 1., 1.,
                                 edgecolor='none') for X, Y in zip(x, y)]

            collection = PatchCollection(patches, norm=norm, cmap=cmap,
                                         edgecolors='none')
            collection.set_array(z)

            return collection

        L_ax.add_collection(scatterRectangles(x=x, y=y, z=z,
                                              norm=norm, cmap=cmap))

        b_ax.add_collection(scatterRectangles(x=numerix.zeros((N,), 'l'), y=numerix.arange(N), z=b,
                                              norm=norm, cmap=cmap))

        ColorbarBase(ax=c_ax, cmap=cmap, norm=norm, orientation='vertical',
                     format=fmt, ticks=loc)

        pyplot.setp((b_ax.get_xticklabels(),
                     b_ax.get_yticklabels(),
                     b_ax.get_xticklines(),
                     b_ax.get_yticklines()), visible=False)

        L_ax.set_xlim(xmin=-0.5, xmax=N-0.5)
        L_ax.set_ylim(ymax=-0.5, ymin=N-0.5)

        b_ax.set_xlim(xmin=-0.5, xmax=0.5)
        b_ax.set_ylim(ymax=-0.5, ymin=N-0.5)

        fig.suptitle(self.title, x=0.5, y=0.95, fontsize=14)

        pyplot.draw()

        rcParams['text.usetex'] = usetex
コード例 #14
0
ファイル: statplot.py プロジェクト: timebridge/fluidity
 def FormatAxis(self, ax2fmt, scale):
     if ax2fmt == 'x':
         setScale = self.ax.set_xscale
         curAxis = self.ax.xaxis
         curData = self.xData
     elif ax2fmt == 'y':
         setScale = self.ax.set_yscale
         curAxis = self.ax.yaxis
         curData = self.yData
     setScale(scale)
     if scale == 'linear':
         self.ax.ticklabel_format(style='sci',
                                  axis=ax2fmt,
                                  scilimits=(0, 0),
                                  useMathText=True)
         curAxis.set_minor_locator(tck.AutoMinorLocator())
         self.ax.relim()
         self.ax.autoscale(True, ax2fmt, None)
     elif scale == 'log':
         curAxis.set_minor_locator(tck.LogLocator(subs=numpy.arange(2, 10)))
         logFmt = tck.LogFormatterSciNotation(base=10,
                                              labelOnlyBase=False,
                                              minor_thresholds=(4, 1))
         curAxis.set_minor_formatter(logFmt)
         self.ax.relim()
         self.ax.autoscale(True, ax2fmt, None)
     elif scale == 'symlog':
         axMin = min(abs(curData[curData != 0]))
         axMax = max(abs(curData))
         axRange = numpy.log10(axMax / axMin)
         if ax2fmt == 'x':
             setScale('symlog',
                      basex=10,
                      subsx=numpy.arange(2, 10),
                      linthreshx=axMin * 10**(axRange / 2))
         elif ax2fmt == 'y':
             setScale('symlog',
                      basey=10,
                      subsy=numpy.arange(2, 10),
                      linthreshy=axMin * 10**(axRange / 2))
         # Thomas Duvernay, 06/01/19
         # There seems to be a bug with the labelling of the 0 tick
         # when a 'symlog' is used as an axis scale. It looks like
         # it is considered as a minor tick.
         symLogLoc = tck.SymmetricalLogLocator(subs=numpy.arange(2, 10),
                                               linthresh=axMin *
                                               10**(axRange / 2),
                                               base=10)
         curAxis.set_minor_locator(symLogLoc)
         logFmt = tck.LogFormatterSciNotation(base=10,
                                              labelOnlyBase=False,
                                              minor_thresholds=(4, 1),
                                              linthresh=axMin *
                                              10**(axRange / 2))
         curAxis.set_minor_formatter(logFmt)
     self.ax.set_xlabel(self.xCombo.get_child().get_text(),
                        fontweight='bold',
                        fontsize=20)
     self.ax.set_ylabel(self.yCombo.get_child().get_text(),
                        fontweight='bold',
                        fontsize=20)
     self.ax.tick_params(which='major', length=7, labelsize=16, width=2)
     self.ax.tick_params(which='minor',
                         length=4,
                         labelsize=10,
                         width=2,
                         colors='xkcd:scarlet',
                         labelrotation=45)
     self.ax.xaxis.get_offset_text().set(fontsize=13,
                                         fontweight='bold',
                                         color='xkcd:black')
     self.ax.yaxis.get_offset_text().set(fontsize=13,
                                         fontweight='bold',
                                         color='xkcd:black')
     self.fig.set_tight_layout(True)
コード例 #15
0
ファイル: plot.py プロジェクト: morris-frank/thesis-tex
def plot_heatmap(data,
                 name,
                 signals=None,
                 ticks="both",
                 minimum="auto",
                 xlabel=None,
                 title=None):
    if ticks == "both":
        ticks = "xy"
    fig, (ax, cbar_ax) = plt.subplots(
        2,
        gridspec_kw=dict(
            left=0.2,
            right=0.95,
            top=0.86,
            bottom=0.1,
            hspace=0.05,
            height_ratios=(0.9, 0.05),
        ),
        figsize=(MARGIN_LENGTH, 1.15 * MARGIN_LENGTH),
    )

    if data.max().max() - data.min().min() > 20:
        norm = colors.SymLogNorm(linthresh=0.001, base=10)
        locator = ticker.SymmetricalLogLocator(linthresh=0.0011, base=10)
        locator.set_params(numticks=5)
    else:
        norm = colors.Normalize()
        locator = ticker.LinearLocator(numticks=5)

    # if minimum == "auto":
    #     _min = data.min().min()
    #     data_min = np.sign(_min) * 10 ** min(10, floor(log10(np.abs(_min))))
    # else:
    #     data_min = minimum
    # data_max = 10 ** max(1, ceil(log10(data.max().max())))
    # _ticks = [data_min, 0, data_max]
    # norm.autoscale(_ticks)

    sns.heatmap(
        data,
        ax=ax,
        annot=False,
        linewidths=1,
        cbar=True,
        cbar_ax=cbar_ax,
        cbar_kws={
            "orientation": "horizontal",
            "ticks": locator
        },
        square=True,
        norm=norm,
        cmap=CMAP_DIV,
    )

    if xlabel is not None:
        ax.set_xlabel(xlabel)
        ax.xaxis.set_label_position('top')

    if title is not None:
        ax.set_title(title)

    ax.tick_params(
        bottom=False,
        left=False,
        labelbottom=False,
        labeltop="x" not in ticks,
        labelleft="y" not in ticks,
    )

    plt.setp(ax.get_yticklabels(),
             rotation=0,
             ha="right",
             rotation_mode="default")

    if signals is not None:
        N = len(signals)
        pos_tick = np.linspace(0, 1, 2 * N + 1)[1::2]
        size = 1 / N * 0.9
        if 'vocals' in signals:
            size *= 1.4

        for i in range(N):
            if "x" in ticks:
                add_plot_tick(ax,
                              signals[i],
                              pos=pos_tick[i],
                              where="x",
                              size=size)
            if "y" in ticks:
                add_plot_tick(ax,
                              signals[i],
                              pos=pos_tick[-i - 1],
                              where="y",
                              size=size)

    savefig(name + "_hm", eps=True)
コード例 #16
0
ファイル: axis_param.py プロジェクト: piScope/piScope
    def _set_ticker(self, a):
        try:
            if not isiterable(self.ticks):
                if self.scale == 'linear':
                    a.set_major_locator(mticker.AutoLocator())
                elif self.scale == 'log':
                    a.set_major_locator(mticker.LogLocator(self.base))
                elif self.scale == 'symlog':
                    from matplotlib.scale import SymmetricalLogScale
                    if isMPL33:
                        scale = SymmetricalLogScale(
                            a,
                            base=self.base,
                            linthresh=self.symloglin,
                            linscale=self.symloglinscale)
                    else:
                        scale = SymmetricalLogScale(
                            a,
                            basex=self.base,
                            linthreshx=self.symloglin,
                            linscalex=self.symloglinscale)
                    a.set_major_locator(
                        mticker.SymmetricalLogLocator(scale.get_transform()))


#                    scale.set_default_locators_and_formatters(a)

                else:
                    a.set_major_locator(mticker.AutoLocator())
                #a.get_axes().locator_params(self.name[0], nbins = 10)
                if self.ticks is not None:
                    value = self.ticks
                else:
                    #figpage = a.get_axes().figobj.get_figpage()
                    figpage = a.axes.figobj.get_figpage()
                    if self.name[0] == 'x':
                        value = figpage.getp('nticks')[0]
                    elif self.name[0] == 'y':
                        value = figpage.getp('nticks')[1]
                    elif self.name[0] == 'z':
                        value = figpage.getp('nticks')[2]
                    else:
                        pass
                try:
                    # this works onlyfor MaxNLocator
                    #a.get_axes().locator_params(self.name[0], nbins = value)
                    a.axes.locator_params(self.name[0], nbins=value)
                except BaseException:
                    # for Symlog and LogLocator
                    a.get_major_locator().numticks = value
            else:
                a.set_ticks(self.ticks)

            if self.format == 'default':
                if self.scale == 'linear':
                    a.set_major_formatter(mticker.ScalarFormatter())
                elif self.scale == 'log':
                    a.set_major_formatter(
                        mticker.LogFormatterMathtext(self.base))
                elif self.scale == 'symlog':
                    a.set_major_formatter(
                        mticker.LogFormatterMathtext(self.base))
                else:
                    a.set_major_formatter(mticker.ScalarFormatter())
            elif self.format == 'scalar':
                a.set_major_formatter(mticker.ScalarFormatter())
            elif self.format == 'scalar(mathtext)':
                a.set_major_formatter(
                    mticker.ScalarFormatter(useOffset=True, useMathText=True))
                a.get_major_formatter().get_offset()
            elif self.format == 'log':
                a.set_major_formatter(mticker.LogFormatter(self.base))
            elif self.format == 'log(mathtext)':
                a.set_major_formatter(mticker.LogFormatterMathtext(self.base))
            elif self.format == 'log(exp)':
                a.set_major_formatter(mticker.LogFormatterExponent(self.base))
            elif self.format == 'none':
                a.set_major_formatter(mticker.NullFormatter())
            else:
                a.set_major_formatter(mticker.FormatStrFormatter(self.format))
        except BaseException:
            import traceback
            traceback.print_exc()
コード例 #17
0
            barlinecols[0].set_linestyle(ls[ibranch])
            barlinecols[1].set_linestyle(ls[ibranch])
            for cap in capsstuff:
                cap.set_markeredgewidth(2)

        ax.set_yscale('symlog', linthreshy=lintreshy)
        ax.set_xscale('symlog', linthreshx=lintreshx)

        ax.set_ylim([-5e-1, 5e-1])
        ticks = np.concatenate([np.arange(-lintreshy, lintreshy, 1e-3)
                                ])  #, np.arange(lintresh, 1e-2, 9)])
        s = ax.yaxis._scale
        ax.yaxis.set_minor_locator(
            ticker.SymmetricalLogLocator(s,
                                         subs=[
                                             1., 2., 3., 4., 5., 6., 7., 8.,
                                             9., -2., -3., -4., -5., -6., -7.,
                                             -8., -9.
                                         ]))
        ticks = np.concatenate(
            [ticks, ax.yaxis.get_minor_locator().tick_values(-.1, .1)])
        ax.yaxis.set_minor_locator(ticker.FixedLocator(ticks))

        ax.set_xlim([-5e-1, 5e-1])
        ticks = np.concatenate([np.arange(-lintreshx, lintreshx, 1e-4)
                                ])  #, np.arange(lintresh, 1e-2, 9)])
        s = ax.xaxis._scale
        ax.xaxis.set_minor_locator(
            ticker.SymmetricalLogLocator(s,
                                         subs=[
                                             1., 2., 3., 4., 5., 6., 7., 8.,
                                             9., -2., -3., -4., -5., -6., -7.,
コード例 #18
0
# Plotting settings
# Note:Many things are commented out as I was experimenting with the type of display
# =============================================================================

fig = plt.figure(figsize=(10, 10))
gs = gridspec.GridSpec(nrows=2, ncols=2)
cmap = plt.cm.RdBu_r

# =============================================================================
# Contour plot of Bx
# =============================================================================
ax0 = fig.add_subplot(gs[0, 0])
norm=colors.SymLogNorm(linthresh=0.000001,linscale=1, vmin=Bx.min(), vmax=Bx.max())
#cs1 = ax0.contourf(x, y, Bx, norm=colors.SymLogNorm(linthresh=0.1,linscale=1, vmin=Bx.min(), vmax=Bx.max()),cmap='RdBu')
#cs1 = ax0.contourf(x, y, Bx,  norm=MidpointNormalize(midpoint=0.,vmin=Bx.min(), vmax=Bx.max()),cmap='RdBu_r')
cs1 = ax0.contourf(x, y, Bx,locator=ticker.SymmetricalLogLocator(base=10, linthresh=0.000001),norm=norm,cmap='RdBu_r')
#cs1 = ax0.contourf(x, y, Bx,norm=colors.SymLogNorm(linthresh=0.1,linscale=0.1,vmin=Bx.min(), vmax=Bx.max()),cmap='RdBu_r')
ax0.set_title("Bx")
#ax0.set_xlabel("x ({})".format(units[unit_size]))
#ax0.set_ylabel("y ({})".format(units[unit_size]))
ax0.set_xlabel(r'$x$ (m)')
ax0.set_ylabel(r'$y$ (m)')
ax0.set_xlim(-XMAX/2, XMAX/2)
ax0.set_ylim(-YMAX/2, YMAX/2)
#ax0.ticklabel_format(axis='both',style='sci',scilimits=(0,0),useMathText=True)
cbar1=fig.colorbar(cs1,ax=ax0)
cbar1.set_label('Log(Bx)',rotation=270)
ax0.add_patch(Rectangle((-XM_Max,-YM_Max),length_mag,width_mag, color='k', zorder=100))

# =============================================================================
# Contour plot of By
コード例 #19
0
fig = plt.figure(figsize=(11, 7))
gs = gridspec.GridSpec(nrows=2, ncols=3)
cmap = plt.cm.RdBu_r

# =============================================================================
# Contour plot of Bx
# =============================================================================
ax0 = fig.add_subplot(gs[0, 0])
norm = colors.SymLogNorm(linthresh=0.000001, linscale=1, vmin=-0.1, vmax=0.1)
#cs1 = ax0.contourf(x, y, Bx, norm=colors.SymLogNorm(linthresh=0.1,linscale=1, vmin=Bx.min(), vmax=Bx.max()),cmap='RdBu')
#cs1 = ax0.contourf(x, y, Bx,  norm=MidpointNormalize(midpoint=0.,vmin=Bx.min(), vmax=Bx.max()),cmap='RdBu_r')
cs1 = ax0.contourf(x2,
                   y2,
                   Bx,
                   locator=ticker.SymmetricalLogLocator(base=10,
                                                        linthresh=0.000001),
                   norm=norm,
                   cmap='RdBu_r')
#cs1 = ax0.contourf(x, y, Bx,norm=colors.SymLogNorm(linthresh=0.1,linscale=0.1,vmin=Bx.min(), vmax=Bx.max()),cmap='RdBu_r')
ax0.set_title("Bx")
#ax0.set_xlabel("x ({})".format(units[unit_size]))
#ax0.set_ylabel("y ({})".format(units[unit_size]))
ax0.set_xlabel(r'x ($\mu$m)')
ax0.set_ylabel(r'y ($\mu$m)')
ax0.set_xlim(-50, 50)
ax0.set_ylim(-50, 50)
#ax0.ticklabel_format(axis='both',style='sci',scilimits=(0,0),useMathText=True)
cbar1 = fig.colorbar(cs1, ax=ax0, extend='both')
cbar1.set_label('Log(Bx)', rotation=270)
ax0.add_patch(Rectangle((-5, -5), 10, 10, color='k', zorder=100))
ax0.add_patch(Circle((12.6, 11), radius=1, color='g', zorder=100))
コード例 #20
0
                                            axt = axs[dpoolind].twiny()
                                            axt.set_xlim(1e6*xcpdps_b_avg_pol_diag[sampling]['lags'].min(), 1e6*xcpdps_b_avg_pol_diag[sampling]['lags'].max())
                                    
                                        axs[dpoolind].axhline(y=0, xmin=0, xmax=1, ls='-', lw=1, color='black')

                                        minvals = NP.asarray(minvals)
                                        maxvals = NP.asarray(maxvals)
                                        minabsvals = NP.asarray(minabsvals)
                                        maxabsvals = NP.asarray(maxabsvals)
                                        axs[dpoolind].set_xlim(0.99*xcpdps_b_avg_pol_diag[sampling]['kprll'][zind,:].min(), 1.01*xcpdps_b_avg_pol_diag[sampling]['kprll'][zind,:].max())
                                        if NP.min(minvals) < 0.0:
                                            axs[dpoolind].set_ylim(1.5*NP.min(minvals), 2*NP.max(maxabsvals))
                                        else:
                                            axs[dpoolind].set_ylim(0.5*NP.min(minvals), 2*NP.max(maxabsvals))
                                        axs[dpoolind].set_yscale('symlog', linthreshy=10**NP.floor(NP.log10(NP.min(minabsvals[minabsvals > 0.0]))))
                                        tickloc = PLTick.SymmetricalLogLocator(linthresh=10**NP.floor(NP.log10(NP.min(minabsvals[minabsvals > 0.0]))), base=100.0)
                                        axs[dpoolind].yaxis.set_major_locator(tickloc)
                                        axs[dpoolind].grid(color='0.9', which='both', linestyle=':', lw=1)
                                        
                                    fig.subplots_adjust(top=0.85)
                                    fig.subplots_adjust(bottom=0.16)
                                    fig.subplots_adjust(left=0.22)
                                    fig.subplots_adjust(right=0.98)
                                                        
                                    big_ax = fig.add_subplot(111)
                                    big_ax.set_facecolor('none') # matplotlib.__version__ >= 2.0.0
                                    # big_ax.set_axis_bgcolor('none') # matplotlib.__version__ < 2.0.0
                                    big_ax.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
                                    big_ax.set_xticks([])
                                    big_ax.set_yticks([])
                                    big_ax.set_xlabel(r'$\kappa_\parallel$'+' [pseudo '+r'$h$'+' Mpc'+r'$^{-1}$'+']', fontsize=12, weight='medium', labelpad=20)
コード例 #21
0
ファイル: show.py プロジェクト: fabiocarrara/meye
def ee(args):
    sns.set_theme(context='notebook', style='whitegrid')

    exps = expman.gather(args.run).filter(args.filter)
    mask_metrics = exps.collect('test_pred/mask_metrics.csv').groupby(
        'exp_id')[['dice', 'iou']].max()
    flops_nparams = exps.collect('flops_nparams.csv')
    data = pd.merge(mask_metrics, flops_nparams, on='exp_id')
    data['dice'] *= 100

    named_data = data.rename(
        {
            'nparams': '# Params',
            'dice': 'mean Dice Coeff. (%)',
            'conv_type': '$t$ (Conv. Type)',
            'grow_factor': r'$\gamma$',
            'num_filters': '$k$ (# Filters)',
            'flops': 'FLOPs',
            'num_stages': '$s$ (# Stages)',
        },
        axis=1).replace({
            'bn-conv': 'conv-bn',
            'sep-bn-conv': 'sep-conv-bn'
        })

    g = sns.relplot(data=named_data,
                    x='FLOPs',
                    y='mean Dice Coeff. (%)',
                    hue='$t$ (Conv. Type)',
                    hue_order=['conv', 'conv-bn', 'sep-conv', 'sep-conv-bn'],
                    col='$s$ (# Stages)',
                    style='$k$ (# Filters)',
                    markers=True,
                    markersize=9,
                    kind='line',
                    dashes=True,
                    facet_kws=dict(despine=False, legend_out=False),
                    legend=True,
                    height=3.8,
                    aspect=1.3,
                    markeredgecolor='white')

    b_formatter = ticker.FuncFormatter(
        lambda x, pos: '{:.2f}'.format(x / 10**9) + 'B')

    h, l = g.axes.flatten()[0].get_legend_handles_labels()
    for hi in h:
        hi.set_markeredgecolor('white')
    g.axes.flatten()[0].legend_.remove()
    g.fig.legend(h,
                 l,
                 ncol=2,
                 bbox_to_anchor=(0.53, 0.53),
                 fancybox=False,
                 columnspacing=0,
                 framealpha=1,
                 handlelength=1.2)

    for ax in g.axes.flatten():
        ax.yaxis.set_minor_locator(ticker.AutoMinorLocator())
        ax.set_ylim(bottom=40, top=90)
        ax.set_xscale('symlog')
        ax.set_xlim(left=0.04 * 10**9, right=2 * 10**9)

        ax.xaxis.set_minor_locator(
            ticker.SymmetricalLogLocator(base=10,
                                         linthresh=2,
                                         subs=[1.5, 2, 3, 4, 5, 6, 8]))
        ax.xaxis.set_minor_formatter(b_formatter)
        ax.grid(which='minor', linestyle='--', color='#eeeeee')

        ax.xaxis.set_major_formatter(b_formatter)
        ax.tick_params(axis="x", which="both", rotation=90)

    plt.savefig(args.output, bbox_inches='tight')
コード例 #22
0
def add_major_minor_ticks(ax,
                          x_minor_per_major=3,
                          y_minor_per_major=3,
                          labelsize="small",
                          basex=10,
                          basey=10,
                          linthreshx=2,
                          linthreshy=2):
    """Utility function to make plots look like NCL plots by adding minor and
    major tick lines.

    Args:

        ax (:class:`matplotlib.axes._subplots.AxesSubplot` or :class:`cartopy.mpl.geoaxes.GeoAxesSubplot`):
            Current axes to the current figure

        x_minor_per_major (:class:`int`):
            Number of minor ticks between adjacent major ticks on x-axis

        y_minor_per_major (:class:`int`):
            Number of minor ticks between adjacent major ticks on y-axis

        labelsize (:class:`str`):
            Optional text size passed to tick_params. A default value of "small" is used if nothing is set.

        basex (:class:`int`):
            If the xaxis scale is logarithmic, this is the base for the logarithm. Default is base 10.

        basey (:class:`int`):
            If the yaxis scale is logarithmic, this is the base for the logarithm. Default is base 10.

        linthreshx (:class:`int`):
            An argument passed to SymmetricalLogLocator if the xaxis scale is
            `symlog`. Defines the range (-x, x), within which the plot is
            linear. This avoids having the plot go to infinity around zero.
            Defaults to 2.

        linthreshy (:class:`int`):
            An argument passed to SymmetricalLogLocator if the yaxis scale is
            `symlog`. Defines the range (-x, x), within which the plot is
            linear. This avoids having the plot go to infinity around zero.
            Defaults to 2.
    """
    import matplotlib.ticker as tic

    ax.tick_params(labelsize=labelsize)
    ax.minorticks_on()
    if ax.xaxis.get_scale() == 'log':
        ax.xaxis.set_minor_locator(
            tic.LogLocator(base=basex,
                           subs=np.linspace(0, basex, x_minor_per_major + 1)))
    elif ax.xaxis.get_scale() == 'symlog':
        ax.xaxis.set_minor_locator(
            tic.SymmetricalLogLocator(base=basex,
                                      subs=np.linspace(0, basex,
                                                       x_minor_per_major + 1),
                                      linthresh=linthreshx))
    else:
        ax.xaxis.set_minor_locator(tic.AutoMinorLocator(n=x_minor_per_major))

    if ax.yaxis.get_scale() == 'log':
        ax.yaxis.set_minor_locator(
            tic.LogLocator(base=basey,
                           subs=np.linspace(0, basey, y_minor_per_major + 1)))
    elif ax.yaxis.get_scale() == 'symlog':
        ax.yaxis.set_minor_locator(
            tic.SymmetricalLogLocator(base=basey,
                                      subs=np.linspace(0, basey,
                                                       y_minor_per_major + 1),
                                      linthresh=linthreshy))
    else:
        ax.yaxis.set_minor_locator(tic.AutoMinorLocator(n=y_minor_per_major))

    # length and width are in points and may need to change depending on figure size etc.
    ax.tick_params(
        "both",
        length=8,
        width=0.9,
        which="major",
        bottom=True,
        top=True,
        left=True,
        right=True,
    )
    ax.tick_params(
        "both",
        length=4,
        width=0.4,
        which="minor",
        bottom=True,
        top=True,
        left=True,
        right=True,
    )