Python matplotlib.colors.LogNorm() Examples

The following are 30 code examples of matplotlib.colors.LogNorm(). 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: analysisfigure.py    From ray-optics with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, fig, gs, pupil_grid, maxdim,
                 yaxis_ticks_position='left', **kwargs):
        self.fig = fig
        self.fig.subplots.append(self)

        self.gs = gs
        self.pupil_grid = pupil_grid
        self.maxdim = maxdim

        if 'title' in kwargs:
            self.title = kwargs.pop('title', None)
        kwargs['cmap'] = kwargs.get('cmap', "RdBu_r")

        if 'norm' in kwargs:
            self.norm = kwargs.pop('norm', None)
        else:
            vmin = kwargs.get('vmin') if 'vmin' in kwargs else None
            vmax = kwargs.get('vmax') if 'vmax' in kwargs else None
            self.norm = LogNorm(vmin=vmin, vmax=vmax)

        self.plot_kwargs = kwargs
        self.yaxis_ticks_position = yaxis_ticks_position

        self.update_data() 
Example #2
Source File: test_colorbar.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def test_colorbar_autotickslog():
    # Test new autotick modes...
    with rc_context({'_internal.classic_mode': False}):
        fig, ax = plt.subplots(2, 1)
        x = np.arange(-3.0, 4.001)
        y = np.arange(-4.0, 3.001)
        X, Y = np.meshgrid(x, y)
        Z = X * Y
        pcm = ax[0].pcolormesh(X, Y, 10**Z, norm=LogNorm())
        cbar = fig.colorbar(pcm, ax=ax[0], extend='both',
                            orientation='vertical')

        pcm = ax[1].pcolormesh(X, Y, 10**Z, norm=LogNorm())
        cbar2 = fig.colorbar(pcm, ax=ax[1], extend='both',
                            orientation='vertical', shrink=0.4)
        np.testing.assert_almost_equal(cbar.ax.yaxis.get_ticklocs(),
                10**np.arange(-12, 12.2, 4.))
        np.testing.assert_almost_equal(cbar2.ax.yaxis.get_ticklocs(),
                10**np.arange(-12, 13., 12.)) 
Example #3
Source File: test_colorbar.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_colorbar_renorm():
    x, y = np.ogrid[-4:4:31j, -4:4:31j]
    z = 120000*np.exp(-x**2 - y**2)

    fig, ax = plt.subplots()
    im = ax.imshow(z)
    cbar = fig.colorbar(im)

    norm = LogNorm(z.min(), z.max())
    im.set_norm(norm)
    cbar.set_norm(norm)
    cbar.locator = LogLocator()
    cbar.formatter = LogFormatter()
    cbar.update_normal(im)
    assert np.isclose(cbar.vmin, z.min())

    norm = LogNorm(z.min() * 1000, z.max() * 1000)
    im.set_norm(norm)
    cbar.set_norm(norm)
    cbar.update_normal(im)
    assert np.isclose(cbar.vmin, z.min() * 1000)
    assert np.isclose(cbar.vmax, z.max() * 1000) 
Example #4
Source File: plotting.py    From smallrnaseq with GNU General Public License v3.0 6 votes vote down vote up
def heatmap(df,fname=None,cmap='seismic',log=False):
    """Plot a heat map"""

    from matplotlib.colors import LogNorm
    f=plt.figure(figsize=(8,8))
    ax=f.add_subplot(111)
    norm=None
    df=df.replace(0,.1)
    if log==True:
        norm=LogNorm(vmin=df.min().min(), vmax=df.max().max())
    hm = ax.pcolor(df,cmap=cmap,norm=norm)
    plt.colorbar(hm,ax=ax,shrink=0.6,norm=norm)
    plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
    plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns, rotation=90)
    #ax.axvline(4, color='gray'); ax.axvline(8, color='gray')
    plt.tight_layout()
    if fname != None:
        f.savefig(fname+'.png')
    return ax 
Example #5
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 #6
Source File: colorbar.py    From Computable with MIT License 6 votes vote down vote up
def _select_locator(self, formatter):
        '''
        select a suitable locator
        '''
        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()
            else:
                locator = ticker.MaxNLocator(nbins=5)
        else:
            b = self._boundaries[self._inside]
            locator = ticker.FixedLocator(b) #, nbins=10)

        self.cbar_axis.set_major_locator(locator) 
Example #7
Source File: mass_age_comparison.py    From TheCannon with MIT License 6 votes vote down vote up
def plot(ax, x, y, xlabel, ylabel, axmin, axmax, text):
    a,b,c, im = ax.hist2d(
            x, y,
            bins=40, norm=LogNorm(), cmap="gray_r",
            range=([axmin,axmax],[axmin,axmax]))
    ax.plot([axmin,axmax], [axmin,axmax], c='k')
    #props = dict(boxstyle='round', facecolor='white', pad=0.1)
    ax.text(
            0.05, 0.8, text, 
            horizontalalignment='left', verticalalignment='bottom', 
            transform=ax.transAxes, fontsize=25)

    ax.set_xlabel(xlabel, fontsize=16)
    ax.set_ylabel(ylabel, fontsize=20)
    ax.tick_params(axis='y', labelsize=20)
    ax.tick_params(axis='x', labelsize=20)
    ax.set_xlim(axmin, axmax)
    ax.set_ylim(axmin, axmax)
    ax.yaxis.set_major_locator(
            MaxNLocator(nbins=5))
    ax.xaxis.set_major_locator(
            MaxNLocator(nbins=5))
    return im 
Example #8
Source File: colorbar.py    From Computable with MIT License 6 votes vote down vote up
def _select_locator(self, formatter):
        '''
        select a suitable locator
        '''
        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()
            else:
                locator = ticker.MaxNLocator(nbins=5)
        else:
            b = self._boundaries[self._inside]
            locator = ticker.FixedLocator(b) #, nbins=10)

        self.cbar_axis.set_major_locator(locator) 
Example #9
Source File: test_colorbar.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def test_colorbar_renorm():
    x, y = np.ogrid[-4:4:31j, -4:4:31j]
    z = 120000*np.exp(-x**2 - y**2)

    fig, ax = plt.subplots()
    im = ax.imshow(z)
    cbar = fig.colorbar(im)

    norm = LogNorm(z.min(), z.max())
    im.set_norm(norm)
    cbar.set_norm(norm)
    cbar.locator = LogLocator()
    cbar.formatter = LogFormatter()
    cbar.update_normal(im)
    assert np.isclose(cbar.vmin, z.min())

    norm = LogNorm(z.min() * 1000, z.max() * 1000)
    im.set_norm(norm)
    cbar.set_norm(norm)
    cbar.update_normal(im)
    assert np.isclose(cbar.vmin, z.min() * 1000)
    assert np.isclose(cbar.vmax, z.max() * 1000) 
Example #10
Source File: colorbar.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def config_axis(self):
        ax = self.ax
        if (isinstance(self.norm, colors.LogNorm)
                and self._use_auto_colorbar_locator()):
            # *both* axes are made log so that determining the
            # mid point is easier.
            ax.set_xscale('log')
            ax.set_yscale('log')

        if self.orientation == 'vertical':
            long_axis, short_axis = ax.yaxis, ax.xaxis
        else:
            long_axis, short_axis = ax.xaxis, ax.yaxis

        long_axis.set_label_position(self.ticklocation)
        long_axis.set_ticks_position(self.ticklocation)
        short_axis.set_ticks([])
        short_axis.set_ticks([], minor=True)
        self._set_label() 
Example #11
Source File: colorbar.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def _reset_locator_formatter_scale(self):
        """
        Reset the locator et al to defaults.  Any user-hardcoded changes
        need to be re-entered if this gets called (either at init, or when
        the mappable normal gets changed: Colorbar.update_normal)
        """
        self.locator = None
        self.formatter = None
        if (isinstance(self.norm, colors.LogNorm)
                and self._use_auto_colorbar_locator()):
            # *both* axes are made log so that determining the
            # mid point is easier.
            self.ax.set_xscale('log')
            self.ax.set_yscale('log')

            self.minorticks_on()
        else:
            self.ax.set_xscale('linear')
            self.ax.set_yscale('linear') 
Example #12
Source File: test_colorbar.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_colorbar_autotickslog():
    # Test new autotick modes...
    with rc_context({'_internal.classic_mode': False}):
        fig, ax = plt.subplots(2, 1)
        x = np.arange(-3.0, 4.001)
        y = np.arange(-4.0, 3.001)
        X, Y = np.meshgrid(x, y)
        Z = X * Y
        pcm = ax[0].pcolormesh(X, Y, 10**Z, norm=LogNorm())
        cbar = fig.colorbar(pcm, ax=ax[0], extend='both',
                            orientation='vertical')

        pcm = ax[1].pcolormesh(X, Y, 10**Z, norm=LogNorm())
        cbar2 = fig.colorbar(pcm, ax=ax[1], extend='both',
                            orientation='vertical', shrink=0.4)
        np.testing.assert_almost_equal(cbar.ax.yaxis.get_ticklocs(),
                10**np.arange(-12, 12.2, 4.))
        np.testing.assert_almost_equal(cbar2.ax.yaxis.get_ticklocs(),
                10**np.arange(-12, 13., 12.)) 
Example #13
Source File: plot_functions.py    From ADNC with Apache License 2.0 6 votes vote down vote up
def plot_weightings(self, weightings, ax, name='Weightings', mode='log', color='YlOrRd'):
        assert weightings.shape.__len__() == 2, "plot weightings: need 2D matrix as data"
        if mode == 'log':
            norm = colors.LogNorm(vmin=1e-3, vmax=1)
        else:
            norm = colors.Normalize(vmin=0, vmax=1)
        img = ax.imshow(np.transpose(weightings), interpolation='nearest', norm=norm, cmap=color,
                        aspect='auto')  # gist_stern
        ax.set_adjustable('box-forced')
        if self.title:
            ax.set_ylabel(name, size=self.text_size)
        if self.legend:
            box = ax.get_position()
            ax.set_position([box.x0 - 0.001, box.y0, box.width, box.height])
            axColor = plt.axes([box.x0 + box.width + 0.005, box.y0, 0.005, box.height])
            cb = plt.colorbar(img, cax=axColor, orientation="vertical")
            for l in cb.ax.yaxis.get_ticklabels():
                l.set_size(self.text_size) 
Example #14
Source File: colorbar.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _select_locator(self, formatter):
        '''
        select a suitable locator
        '''
        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()
            else:
                locator = ticker.MaxNLocator(nbins=5)
        else:
            b = self._boundaries[self._inside]
            locator = ticker.FixedLocator(b) #, nbins=10)

        self.cbar_axis.set_major_locator(locator) 
Example #15
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 #16
Source File: colorbar.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def config_axis(self):
        ax = self.ax
        if (isinstance(self.norm, colors.LogNorm)
                and self._use_auto_colorbar_locator()):
            # *both* axes are made log so that determining the
            # mid point is easier.
            ax.set_xscale('log')
            ax.set_yscale('log')

        if self.orientation == 'vertical':
            long_axis, short_axis = ax.yaxis, ax.xaxis
        else:
            long_axis, short_axis = ax.xaxis, ax.yaxis

        long_axis.set_label_position(self.ticklocation)
        long_axis.set_ticks_position(self.ticklocation)
        short_axis.set_ticks([])
        short_axis.set_ticks([], minor=True)

        self._set_label() 
Example #17
Source File: colorbar.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def config_axis(self):
        ax = self.ax
        if (isinstance(self.norm, colors.LogNorm)
                and self._use_auto_colorbar_locator()):
            # *both* axes are made log so that determining the
            # mid point is easier.
            ax.set_xscale('log')
            ax.set_yscale('log')

        if self.orientation == 'vertical':
            long_axis, short_axis = ax.yaxis, ax.xaxis
        else:
            long_axis, short_axis = ax.xaxis, ax.yaxis

        long_axis.set_label_position(self.ticklocation)
        long_axis.set_ticks_position(self.ticklocation)
        short_axis.set_ticks([])
        short_axis.set_ticks([], minor=True)
        self._set_label() 
Example #18
Source File: sgd.py    From tf-matplotlib with MIT License 6 votes vote down vote up
def init_fig(*args, **kwargs):
            '''Initialize figures.'''
            fig = tfmpl.create_figure(figsize=(8,6))
            ax = fig.add_subplot(111, projection='3d', elev=50, azim=-30)
            ax.w_xaxis.set_pane_color((1.0,1.0,1.0,1.0))
            ax.w_yaxis.set_pane_color((1.0,1.0,1.0,1.0))
            ax.w_zaxis.set_pane_color((1.0,1.0,1.0,1.0))
            ax.set_title('Gradient descent on Beale surface')
            ax.set_xlabel('$x$')
            ax.set_ylabel('$y$')
            ax.set_zlabel('beale($x$,$y$)')
        
            xx, yy = np.meshgrid(np.linspace(-4.5, 4.5, 40), np.linspace(-4.5, 4.5, 40))
            zz = beale(xx, yy)
            ax.plot_surface(xx, yy, zz, norm=LogNorm(), rstride=1, cstride=1, edgecolor='none', alpha=.8, cmap=cm.jet)
            ax.plot([3], [.5], [beale(3, .5)], 'k*', markersize=5)
            
            for o in optimizers:
                path, = ax.plot([],[],[], label=o[1])
                paths.append(path)

            ax.legend(loc='upper left')
            fig.tight_layout()

            return fig, paths 
Example #19
Source File: colorbar.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def _select_locator(self, formatter):
        '''
        select a suitable locator
        '''
        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()
            else:
                locator = ticker.MaxNLocator(nbins=5)
        else:
            b = self._boundaries[self._inside]
            locator = ticker.FixedLocator(b) #, nbins=10)

        self.cbar_axis.set_major_locator(locator) 
Example #20
Source File: colorbar.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def _select_locator(self, formatter):
        '''
        select a suitable locator
        '''
        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()
            else:
                locator = ticker.MaxNLocator(nbins=5)
        else:
            b = self._boundaries[self._inside]
            locator = ticker.FixedLocator(b) #, nbins=10)

        self.cbar_axis.set_major_locator(locator) 
Example #21
Source File: example_fwding_summary.py    From lndmanage with MIT License 6 votes vote down vote up
def plot_fees(forwarding_events):
    """
    Plots forwarding fees and effective fee rate in color code.

    :param forwarding_events:
    """
    times = []
    amounts = []
    color = []
    for f in forwarding_events:
        times.append(datetime.datetime.fromtimestamp(f['timestamp']))
        amounts.append(f['fee_msat'])
        color.append(f['effective_fee'])
    plt.xticks(rotation=45)
    plt.scatter(times, amounts, c=color, norm=colors.LogNorm(vmin=1E-6, vmax=1E-3), s=2)
    plt.yscale('log')
    plt.ylabel('Fees [msat]')
    plt.ylim((0.5, 1E+6))
    plt.colorbar(label='effective feerate (base + rate)')
    plt.show() 
Example #22
Source File: filter.py    From picasso with MIT License 5 votes vote down vote up
def plot(self):
        # Prepare the data
        x = self.locs[self.field_x]
        y = self.locs[self.field_y]
        valid = np.isfinite(x) & np.isfinite(y)
        x = x[valid]
        y = y[valid]
        # Prepare the figure
        self.figure.clear()
        # self.canvas.figure = self.figure
        axes = self.figure.add_subplot(111)
        # Start hist2 version
        bins_x = lib.calculate_optimal_bins(x, 1000)
        bins_y = lib.calculate_optimal_bins(y, 1000)
        counts, x_edges, y_edges, image = axes.hist2d(
            x, y, bins=[bins_x, bins_y], norm=LogNorm()
        )
        x_range = x.ptp()
        axes.set_xlim([bins_x[0] - 0.05 * x_range, x.max() + 0.05 * x_range])
        y_range = y.ptp()
        axes.set_ylim([bins_y[0] - 0.05 * y_range, y.max() + 0.05 * y_range])
        self.figure.colorbar(image, ax=axes)
        axes.grid(False)
        axes.get_xaxis().set_label_text(self.field_x)
        axes.get_yaxis().set_label_text(self.field_y)
        self.selector = RectangleSelector(
            axes,
            self.on_rect_select,
            useblit=False,
            rectprops=dict(facecolor="green", alpha=0.2, fill=True),
        )
        self.canvas.draw() 
Example #23
Source File: pncview.py    From pseudonetcdf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def presslat(ifile, varkey, options, before='', after=''):
    import matplotlib.pyplot as plt
    from matplotlib.colors import Normalize, LogNorm
    outpath = getattr(options, 'outpath', '.')
    vert = cu.getpresbnds(ifile)
    lat, latunit = cu.getlatbnds(ifile)
    lat = np.append(lat.squeeze()[..., :2].mean(
        1), lat.squeeze()[-1, 2:].mean(0))
    var = ifile.variables[varkey]
    dims = [(k, l) for l, k in zip(var[:].shape, var.dimensions) if l > 1]
    if len(dims) > 2:
        raise ValueError(
            'Press-lat can have 2 non-unity dimensions; got %d - %s' %
            (len(dims), str(dims)))
    if options.logscale:
        norm = LogNorm()
    else:
        norm = Normalize()
    exec(before)
    ax = plt.gca()
    print(varkey, end='')
    patches = ax.pcolor(lat, vert, var[:].squeeze(), norm=norm)
    # ax.set_xlabel(X.units.strip())
    # ax.set_ylabel(Y.units.strip())
    cbar = plt.colorbar(patches)
    vunit = getattr(var, 'units', 'unknown').strip()
    cbar.set_label(varkey + ' (' + vunit + ')')
    cbar.ax.text(.5, 1, '%.2g' % var[:].max(
    ), horizontalalignment='center', verticalalignment='bottom')
    cbar.ax.text(.5, 0, '%.2g' % var[:].min(
    ), horizontalalignment='center', verticalalignment='top')
    ax.set_ylim(vert.max(), vert.min())
    ax.set_xlim(lat.min(), lat.max())
    fmt = 'png'
    figpath = os.path.join(outpath + '_PRESSLAT_' + varkey + '.' + fmt)
    exec(after)
    plt.savefig(figpath)
    print('Saved fig', figpath)
    return figpath 
Example #24
Source File: plot_functions.py    From ADNC with Apache License 2.0 5 votes vote down vote up
def plot_matrix(self, matrix, ax, name='Weightings', mode='norm', color='RdYlBu', zero_width=5, zero_add='zeros'):
        assert matrix.shape.__len__() == 3, "plot weightings: need 3D matrix as data"

        if mode == 'log':
            norm = colors.LogNorm(vmin=1e-8, vmax=0.1)
        elif mode == 'norm1':
            norm = colors.Normalize(vmin=0, vmax=1)
        else:
            norm = colors.Normalize(vmin=-1, vmax=1)

        if zero_add == 'zeros':
            matrix = np.concatenate([matrix, np.zeros([matrix.shape[0], matrix.shape[1], zero_width])], axis=2)
            matrix = np.transpose(matrix, axes=(0, 2, 1))
            flat_matrix = np.reshape(matrix, [-1, matrix.shape[2]])
            flat_matrix = np.concatenate([np.zeros([zero_width, flat_matrix.shape[1]]), flat_matrix], axis=0)
        else:
            matrix = np.concatenate([matrix, np.ones([matrix.shape[0], matrix.shape[1], zero_width])], axis=2)
            matrix = np.transpose(matrix, axes=(0, 2, 1))
            flat_matrix = np.reshape(matrix, [-1, matrix.shape[2]])
            flat_matrix = np.concatenate([np.ones([zero_width, flat_matrix.shape[1]]), flat_matrix], axis=0)

        img = ax.imshow(np.transpose(flat_matrix), aspect='auto', interpolation='nearest', norm=norm, cmap=color)

        ax.set_adjustable('box-forced')
        if self.title:
            ax.set_ylabel(name, size=self.text_size)
        if self.legend:
            box = ax.get_position()
            ax.set_position([box.x0 - 0.001, box.y0, box.width, box.height])
            axColor = plt.axes([box.x0 + box.width + 0.005, box.y0, 0.005, box.height])
            cb = plt.colorbar(img, cax=axColor, orientation="vertical")
            for l in cb.ax.yaxis.get_ticklabels():
                l.set_size(self.text_size)
            tick_locator = ticker.MaxNLocator(nbins=3)
            cb.locator = tick_locator
            cb.update_ticks() 
Example #25
Source File: plot_functions.py    From ADNC with Apache License 2.0 5 votes vote down vote up
def plot_vector_as_matrix(self, vector, vertical, repeats, ax, name='Weightings', mode='log', color='YlOrRd',
                              zero_width=5):

        assert vector.shape.__len__() == 2, "plot weightings: need 2D matrix as data"

        if mode == 'log':
            norm = colors.LogNorm(vmin=1e-3, vmax=1)
        elif mode == 'norm1':
            norm = colors.Normalize(vmin=0, vmax=1)
        else:
            norm = colors.Normalize(vmin=-1, vmax=1)

        if vertical:
            matrix = np.repeat(vector, repeats, axis=1)
            matrix = np.reshape(matrix, [vector.shape[0], vector.shape[1], repeats])

        else:

            matrix = np.repeat(vector, repeats, axis=0)
            matrix = np.reshape(matrix, [vector.shape[0], repeats, vector.shape[1]])

        matrix = np.concatenate([matrix, np.zeros([matrix.shape[0], matrix.shape[1], zero_width])], axis=2)
        matrix = np.transpose(matrix, axes=(0, 2, 1))
        flat_matrix = np.reshape(matrix, [-1, matrix.shape[2]])
        flat_matrix = np.concatenate([np.zeros([zero_width, flat_matrix.shape[1]]), flat_matrix], axis=0)

        img = ax.imshow(np.transpose(flat_matrix), aspect='auto', interpolation='nearest', norm=norm, cmap=color)

        ax.set_adjustable('box-forced')
        box = ax.get_position()
        ax.set_position([box.x0 - 0.001, box.y0, box.width, box.height])

        if self.legend:
            axColor = plt.axes([box.x0 + box.width + 0.005, box.y0, 0.005, box.height])
            cb = plt.colorbar(img, cax=axColor, orientation="vertical")
            for l in cb.ax.yaxis.get_ticklabels():
                l.set_size(self.text_size)
        if self.title:
            ax.set_ylabel(name, labelpad=30, size=self.text_size)
        ax.set_yticks([]) 
Example #26
Source File: pointtracker.py    From qkit with GNU General Public License v2.0 5 votes vote down vote up
def plot(self, all=True, amount=1, log=False):
        """
        Plot the data with an overlay of the detected points.
        
        Keyword arguments:
            all (bool)   -- plot all detected traces (default: True)
            amount (int) -- plot given amount of traces (default: 1)
            log (bool)   -- plot data logarithmically (default: False)
        """
        
        fig, axes = plt.subplots(figsize=(16,8))
        
        
        if log==False:
            plt.pcolormesh(self.xdata, self.ydata, self.data.T, cmap="viridis")
        else:
            plt.pcolormesh(self.xdata, self.ydata, self.data.T, cmap="viridis", norm=LogNorm(vmin=self.data.min(), vmax=self.data.max()))
        plt.xlim(min(self.xdata), max(self.xdata))
        plt.ylim(min(self.ydata), max(self.ydata))
        plt.colorbar()
        
        if all:
            n = len(self.x_results)
        else:
            n = amount
        col = ["r", "w", "m", "k", "b", "g", "c", "y"]
        if n>len(col):
            m=int(n/len(col)+1)
            col=m*col
        
        for i in range(0,n):
            plt.plot(self.xdata[self.x_results[i]], self.ydata[self.y_results[i]], col[i]+"x", label="Trace %d"%(i))
        
        plt.legend() 
Example #27
Source File: visualize_pySDC_with_PETSc.py    From pySDC with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def visualize_matrix(result=None):
    """
    Visualizes runtimes in a matrix (cores in space vs. cores in time)

    Args:
        result: dictionary containing the runtimes
    """
    process_list = [1, 2, 4, 6, 12, 24]
    dim = len(process_list)
    mat = np.zeros((dim, dim))
    tmin = 1E03
    tmax = 0
    for key, item in result.items():
        mat[process_list.index(key[0]), process_list.index(key[1])] = item
        tmin = min(tmin, item)
        tmax = max(tmax, item)

    plt_helper.setup_mpl()
    plt_helper.newfig(textwidth=120, scale=1.5)
    cmap = plt_helper.plt.get_cmap('RdYlGn_r')
    new_cmap = truncate_colormap(cmap, 0.1, 0.9)
    plt_helper.plt.imshow(mat.T, origin='lower', norm=colors.LogNorm(vmin=tmin, vmax=tmax), cmap=new_cmap,
                          aspect='auto')

    for key, item in result.items():
        timing = "{:3.1f}".format(item)
        plt_helper.plt.annotate(timing, xy=(process_list.index(key[0]), process_list.index(key[1])), size='x-small',
                                ha='center', va='center')

    plt_helper.plt.xticks(range(dim), process_list)
    plt_helper.plt.yticks(range(dim), process_list)
    plt_helper.plt.xlabel('Cores in space')
    plt_helper.plt.ylabel('Cores in time')

    fname = 'data/runtimes_matrix_heat'
    plt_helper.savefig(fname)

    assert os.path.isfile(fname + '.pdf'), 'ERROR: plotting did not create PDF file'
    assert os.path.isfile(fname + '.pgf'), 'ERROR: plotting did not create PGF file'
    assert os.path.isfile(fname + '.png'), 'ERROR: plotting did not create PNG file' 
Example #28
Source File: pncview.py    From pseudonetcdf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def tileplot(ifile, varkey, options, before='', after=''):
    import matplotlib.pyplot as plt
    from matplotlib.colors import Normalize, LogNorm
    outpath = getattr(options, 'outpath', '.')
    var = ifile.variables[varkey]
    if options.logscale:
        norm = LogNorm()
    else:
        norm = Normalize()
    exec(before)
    ax = plt.gca()
    print(varkey, end='')
    dims = [(k, l) for l, k in zip(var[:].shape, var.dimensions) if l > 1]
    if len(dims) > 2:
        raise ValueError(
            'Tile plots can have 2 non-unity dimensions; got %d - %s' %
            (len(dims), str(dims)))
    patches = ax.pcolor(var[:].squeeze(), norm=norm)
    ax.set_xlim(0, var[:].squeeze().shape[1])
    ax.set_ylim(0, var[:].squeeze().shape[0])
    ax.set_xlabel(dims[1][0])
    ax.set_ylabel(dims[0][0])
    # ax.set_xlabel(X.units.strip())
    # ax.set_ylabel(Y.units.strip())
    cbar = plt.colorbar(patches)
    vunit = getattr(var, 'units', 'unknown').strip()
    cbar.set_label(varkey + ' (' + vunit + ')')
    cbar.ax.text(.5, 1, '%.2g' % var[:].max(
    ), horizontalalignment='center', verticalalignment='bottom')
    cbar.ax.text(.5, 0, '%.2g' % var[:].min(
    ), horizontalalignment='center', verticalalignment='top')
    fmt = 'png'
    figpath = os.path.join(outpath + '_2D_' + varkey + '.' + fmt)
    exec(after)
    plt.savefig(figpath)
    print('Saved fig', figpath)
    return figpath 
Example #29
Source File: pncview.py    From pseudonetcdf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def pressx(ifile, varkey, options, before='', after=''):
    import matplotlib.pyplot as plt
    from matplotlib.colors import Normalize, LogNorm
    outpath = getattr(options, 'outpath', '.')
    vert = cu.getpresbnds(ifile)
    var = ifile.variables[varkey]
    dims = [(k, l) for l, k in zip(var[:].shape, var.dimensions) if l > 1]
    if len(dims) > 2:
        raise ValueError(
            'Press-x can have 2 non-unity dimensions; got %d - %s' %
            (len(dims), str(dims)))
    if options.logscale:
        norm = LogNorm()
    else:
        norm = Normalize()
    exec(before)
    ax = plt.gca()
    print(varkey, end='')
    vals = var[:].squeeze()
    x = np.arange(vals.shape[1])
    patches = ax.pcolor(x, vert, vals, norm=norm)
    # ax.set_xlabel(X.units.strip())
    # ax.set_ylabel(Y.units.strip())
    plt.colorbar(patches)
    ax.set_ylim(vert.max(), vert.min())
    ax.set_xlim(x.min(), x.max())
    fmt = 'png'
    figpath = os.path.join(outpath + '_PRESX_' + varkey + '.' + fmt)
    exec(after)
    plt.savefig(figpath)
    print('Saved fig', figpath)
    return figpath 
Example #30
Source File: pncview.py    From pseudonetcdf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def presslon(ifile, varkey, options, before='', after=''):
    import matplotlib.pyplot as plt
    from matplotlib.colors import Normalize, LogNorm
    outpath = getattr(options, 'outpath', '.')
    vert = cu.getpresbnds(ifile)
    lon, lonunit = cu.getlonbnds(ifile)
    lon = np.append(lon.squeeze()[..., [0, 3]].mean(
        1), lon.squeeze()[-1, [1, 2]].mean(0))
    var = ifile.variables[varkey]
    dims = [(k, l) for l, k in zip(var[:].shape, var.dimensions) if l > 1]
    if len(dims) > 2:
        raise ValueError(
            'Press-lon plots can have 2 non-unity dimensions; got %d - %s' %
            (len(dims), str(dims)))
    if options.logscale:
        norm = LogNorm()
    else:
        norm = Normalize()
    exec(before)
    ax = plt.gca()
    print(varkey, end='')
    patches = ax.pcolor(lon, vert, var[:].squeeze(), norm=norm)
    # ax.set_xlabel(X.units.strip())
    # ax.set_ylabel(Y.units.strip())
    cbar = plt.colorbar(patches)
    vunit = getattr(var, 'units', 'unknown').strip()
    cbar.set_label(varkey + ' (' + vunit + ')')
    cbar.ax.text(.5, 1, '%.2g' % var[:].max(
    ), horizontalalignment='center', verticalalignment='bottom')
    cbar.ax.text(.5, 0, '%.2g' % var[:].min(
    ), horizontalalignment='center', verticalalignment='top')

    ax.set_ylim(vert.max(), vert.min())
    ax.set_xlim(lon.min(), lon.max())
    fmt = 'png'
    figpath = os.path.join(outpath + '_PRESLON_' + varkey + '.' + fmt)
    exec(after)
    plt.savefig(figpath)
    print('Saved fig', figpath)
    return figpath