Python matplotlib.ticker.MaxNLocator() Examples

The following are 30 code examples of matplotlib.ticker.MaxNLocator(). 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.ticker , or try the search function .
Example #1
Source File: test_constrainedlayout.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_constrained_layout6():
    'Test constrained_layout for nested gridspecs'
    fig = plt.figure(constrained_layout=True)
    gs = fig.add_gridspec(1, 2, figure=fig)
    gsl = gs[0].subgridspec(2, 2)
    gsr = gs[1].subgridspec(1, 2)
    axsl = []
    for gs in gsl:
        ax = fig.add_subplot(gs)
        axsl += [ax]
        example_plot(ax, fontsize=12)
    ax.set_xlabel('x-label\nMultiLine')
    axsr = []
    for gs in gsr:
        ax = fig.add_subplot(gs)
        axsr += [ax]
        pcm = example_pcolor(ax, fontsize=12)

    fig.colorbar(pcm, ax=axsr,
                 pad=0.01, shrink=0.99, location='bottom',
                 ticks=ticker.MaxNLocator(nbins=5)) 
Example #2
Source File: plot.py    From espnet with Apache License 2.0 6 votes vote down vote up
def _plot_and_save_attention(att_w, filename):
    """Plot and save an attention."""
    # dynamically import matplotlib due to not found error
    from matplotlib.ticker import MaxNLocator
    import os

    d = os.path.dirname(filename)
    if not os.path.exists(d):
        os.makedirs(d)
    w, h = plt.figaspect(1.0 / len(att_w))
    fig = plt.Figure(figsize=(w * 2, h * 2))
    axes = fig.subplots(1, len(att_w))
    if len(att_w) == 1:
        axes = [axes]
    for ax, aw in zip(axes, att_w):
        # plt.subplot(1, len(att_w), h)
        ax.imshow(aw, aspect="auto")
        ax.set_xlabel("Input")
        ax.set_ylabel("Output")
        ax.xaxis.set_major_locator(MaxNLocator(integer=True))
        ax.yaxis.set_major_locator(MaxNLocator(integer=True))
    fig.tight_layout()
    return fig 
Example #3
Source File: contour.py    From neural-network-animation with MIT License 6 votes vote down vote up
def _autolev(self, z, N):
        """
        Select contour levels to span the data.

        We need two more levels for filled contours than for
        line contours, because for the latter we need to specify
        the lower and upper boundary of each range. For example,
        a single contour boundary, say at z = 0, requires only
        one contour line, but two filled regions, and therefore
        three levels to provide boundaries for both regions.
        """
        if self.locator is None:
            if self.logscale:
                self.locator = ticker.LogLocator()
            else:
                self.locator = ticker.MaxNLocator(N + 1)
        zmax = self.zmax
        zmin = self.zmin
        lev = self.locator.tick_values(zmin, zmax)
        self._auto = True
        if self.filled:
            return lev
        # For line contours, drop levels outside the data range.
        return lev[(lev > zmin) & (lev < zmax)] 
Example #4
Source File: contour.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def _autolev(self, z, N):
        """
        Select contour levels to span the data.

        We need two more levels for filled contours than for
        line contours, because for the latter we need to specify
        the lower and upper boundary of each range. For example,
        a single contour boundary, say at z = 0, requires only
        one contour line, but two filled regions, and therefore
        three levels to provide boundaries for both regions.
        """
        if self.locator is None:
            if self.logscale:
                self.locator = ticker.LogLocator()
            else:
                self.locator = ticker.MaxNLocator(N + 1)
        zmax = self.zmax
        zmin = self.zmin
        lev = self.locator.tick_values(zmin, zmax)
        self._auto = True
        if self.filled:
            return lev
        # For line contours, drop levels outside the data range.
        return lev[(lev > zmin) & (lev < zmax)] 
Example #5
Source File: plotter.py    From ChainConsumer with MIT License 6 votes vote down vote up
def _plot_walk(self, ax, parameter, data, truth=None, extents=None, convolve=None, color=None, log_scale=False):  # pragma: no cover
        if extents is not None:
            ax.set_ylim(extents)
        assert convolve is None or isinstance(convolve, int), "Convolve must be an integer pixel window width"
        x = np.arange(data.size)
        ax.set_xlim(0, x[-1])
        ax.set_ylabel(parameter)
        if color is None:
            color = "#0345A1"
        ax.scatter(x, data, c=color, s=2, marker=".", edgecolors="none", alpha=0.5)
        max_ticks = self.parent.config["max_ticks"]
        if log_scale:
            ax.set_yscale("log")
            ax.yaxis.set_major_locator(LogLocator(numticks=max_ticks))
        else:
            ax.yaxis.set_major_locator(MaxNLocator(max_ticks, prune="lower"))

        if convolve is not None:
            color2 = self.parent.color_finder.scale_colour(color, 0.5)
            filt = np.ones(convolve) / convolve
            filtered = np.convolve(data, filt, mode="same")
            ax.plot(x[:-1], filtered[:-1], ls=":", color=color2, alpha=1) 
Example #6
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 #7
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 #8
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 #9
Source File: contour.py    From Computable with MIT License 6 votes vote down vote up
def _autolev(self, z, N):
        """
        Select contour levels to span the data.

        We need two more levels for filled contours than for
        line contours, because for the latter we need to specify
        the lower and upper boundary of each range. For example,
        a single contour boundary, say at z = 0, requires only
        one contour line, but two filled regions, and therefore
        three levels to provide boundaries for both regions.
        """
        if self.locator is None:
            if self.logscale:
                self.locator = ticker.LogLocator()
            else:
                self.locator = ticker.MaxNLocator(N + 1)
        zmax = self.zmax
        zmin = self.zmin
        lev = self.locator.tick_values(zmin, zmax)
        self._auto = True
        if self.filled:
            return lev
        # For line contours, drop levels outside the data range.
        return lev[(lev > zmin) & (lev < zmax)] 
Example #10
Source File: plotting.py    From tobac with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def make_map(axes):
    import matplotlib.ticker as mticker
    import cartopy.crs as ccrs
    from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER

    gl = axes.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                      linewidth=2, color='gray', alpha=0.5, linestyle='-')
    axes.coastlines('10m')

    gl.xlabels_top = False
    gl.ylabels_right = False
    gl.xlocator = mticker.MaxNLocator(nbins=5,min_n_ticks=3,steps=None)
    gl.ylocator = mticker.MaxNLocator(nbins=5,min_n_ticks=3,steps=None)
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    #gl.xlabel_style = {'size': 15, 'color': 'gray'}
    #gl.xlabel_style = {'color': 'red', 'weight': 'bold'}
    return axes 
Example #11
Source File: utils.py    From noise2noise-pytorch with MIT License 6 votes vote down vote up
def plot_per_epoch(ckpt_dir, title, measurements, y_label):
    """Plots stats (train/valid loss, avg PSNR, etc.)."""

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(range(1, len(measurements) + 1), measurements)
    ax.xaxis.set_major_locator(MaxNLocator(integer=True))
    ax.set_xlabel('Epoch')
    ax.set_ylabel(y_label)
    ax.set_title(title)
    plt.tight_layout()

    fname = '{}.png'.format(title.replace(' ', '-').lower())
    plot_fname = os.path.join(ckpt_dir, fname)
    plt.savefig(plot_fname, dpi=200)
    plt.close() 
Example #12
Source File: assess_homopolymers.py    From pomoxis with Mozilla Public License 2.0 6 votes vote down vote up
def plot_relative_lengths(data, fname):
    # some panels will be empty for longer HPs so keep track of what lengths and bases are in each row/column
    rows = sorted(data['ref_len'].unique())
    cols = sorted(data['q_base'].unique())
    fig, axes = plt.subplots(
        ncols=len(cols), nrows=len(rows), sharex=True,
        figsize=(4 * len(cols), 2 * len(rows)))
    for rl, rl_df in data.groupby(['ref_len']):
        i = rows.index(rl)
        for qb, qb_df in rl_df.groupby('q_base'):
            j = cols.index(qb)
            ax = axes[i][j]
            ax.bar(qb_df['rel_len'], qb_df['count'])
            ax.set_title('{}{}'.format(qb, rl))
            ax.xaxis.set_tick_params(which='both', labelbottom=True)
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            ax.yaxis.set_major_locator(MaxNLocator(integer=True))

    for ax in axes[-1,:]:
        ax.set_xlabel('Query length relative to reference')
    for ax in axes[:, 0]:
        ax.set_ylabel('Counts')
    fig.tight_layout()
    fig.savefig(fname) 
Example #13
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 #14
Source File: graph_rmse.py    From netflix with MIT License 5 votes vote down vote up
def get_figure_and_axes_for_feature_vs_learn(info):
    title = ('Features vs. Learning Rates ({train} to {test})\n {e} Epochs'
             .format(train=info.train_set_name,
                     test=info.test_set_name,
                     e=info.num_epochs))
    figure = plt.figure()
    figure.canvas.set_window_title(title)
    axes = figure.add_subplot(111, projection='3d')
    axes.get_xaxis().set_major_locator(MaxNLocator(integer=True))
    axes.set_title(title)
    axes.set_xlabel('Number of Features')
    axes.set_ylabel('Learning Rate')
    axes.set_zlabel('RMSE ')
    return figure, axes 
Example #15
Source File: graph_rmse.py    From netflix with MIT License 5 votes vote down vote up
def get_figure_and_axes_for_epoch_vs_learn(info):
    title = ('Epochs vs. Learning Rates ({train} to {test})\n {f} Features'
             .format(train=info.train_set_name,
                     test=info.test_set_name,
                     f=info.num_features))
    figure = plt.figure()
    figure.canvas.set_window_title(title)
    axes = figure.add_subplot(111, projection='3d')
    axes.get_xaxis().set_major_locator(MaxNLocator(integer=True))
    axes.set_title(title)
    axes.set_xlabel('Number of Epochs')
    axes.set_ylabel('Learning Rate')
    axes.set_zlabel('RMSE ')
    return figure, axes 
Example #16
Source File: test_ticker.py    From ImageFusion with MIT License 5 votes vote down vote up
def test_MaxNLocator():
    loc = mticker.MaxNLocator(nbins=5)
    test_value = np.array([20., 40., 60., 80., 100.])
    assert_almost_equal(loc.tick_values(20, 100), test_value)

    test_value = np.array([0., 0.0002, 0.0004, 0.0006, 0.0008, 0.001])
    assert_almost_equal(loc.tick_values(0.001, 0.0001), test_value)

    test_value = np.array([-1.0e+15, -5.0e+14, 0e+00, 5e+14, 1.0e+15])
    assert_almost_equal(loc.tick_values(-1e15, 1e15), test_value) 
Example #17
Source File: colorbar.py    From marvin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _set_cbticks(cbrange, cb_kws):
    """Set colorbar ticks.

    Adjust colorbar range if using a discrete colorbar so that the ticks fall
        in the middle of each level.

    Parameters:
        cbrange (list):
            Colorbar range.
        cb_kws (dict):
            Keyword args to set and draw colorbar.

    Return:
        tuple: colorbar range, colorbar tick numbers
    """
    if cb_kws.get('log_cb'):
        ticks = _log_cbticks(cbrange)
    else:
        try:
            ticks = MaxNLocator(cb_kws.get('n_ticks', 7)).tick_values(*cbrange)
        except AttributeError:
            print('AttributeError: MaxNLocator instance has no attribute ``tick_values``.')

    # if discrete colorbar, offset upper and lower cbrange so ticks are in center of each level
    if cb_kws.get('n_levels', None) is not None:
        offset = (ticks[1] - ticks[0]) / 2.
        cbrange = [ticks[0] - offset, ticks[-1] + offset]
        if cb_kws.get('tick_everyother', False):
            ticks = ticks[::2]

    return cbrange, ticks 
Example #18
Source File: element.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _adjust_cbar(self, cbar, label, dim):
        noalpha = math.floor(self.style[self.cyclic_index].get('alpha', 1)) == 1

        for lb in ['clabel', 'labels']:
            labelsize = self._fontsize(lb, common=False).get('fontsize')
            if labelsize is not None:
                break

        if (cbar.solids and noalpha):
            cbar.solids.set_edgecolor("face")
        cbar.set_label(label, fontsize=labelsize)
        if isinstance(self.cbar_ticks, ticker.Locator):
            cbar.ax.yaxis.set_major_locator(self.cbar_ticks)
        elif self.cbar_ticks == 0:
            cbar.set_ticks([])
        elif isinstance(self.cbar_ticks, int):
            locator = ticker.MaxNLocator(self.cbar_ticks)
            cbar.ax.yaxis.set_major_locator(locator)
        elif isinstance(self.cbar_ticks, list):
            if all(isinstance(t, tuple) for t in self.cbar_ticks):
                ticks, labels = zip(*self.cbar_ticks)
            else:
                ticks, labels = zip(*[(t, dim.pprint_value(t))
                                        for t in self.cbar_ticks])
            cbar.set_ticks(ticks)
            cbar.set_ticklabels(labels)

        for tk in ['cticks', 'ticks']:
            ticksize = self._fontsize(tk, common=False).get('fontsize')
            if ticksize is not None:
                cbar.ax.tick_params(labelsize=ticksize)
                break 
Example #19
Source File: encoder_base.py    From neural_sp with Apache License 2.0 5 votes vote down vote up
def _plot_attention(self, save_path=None, n_cols=2):
        """Plot attention for each head in all encoder layers."""
        from matplotlib import pyplot as plt
        from matplotlib.ticker import MaxNLocator

        # Clean directory
        if save_path is not None and os.path.isdir(save_path):
            shutil.rmtree(save_path)
            os.mkdir(save_path)

        if not hasattr(self, 'aws_dict'):
            return

        for k, aw in self.aws_dict.items():
            lth = k.split('_')[-1].replace('layer', '')
            elens_l = self.data_dict['elens' + lth]

            plt.clf()
            n_heads = aw.shape[1]
            n_cols_tmp = 1 if n_heads == 1 else n_cols
            fig, axes = plt.subplots(max(1, n_heads // n_cols_tmp), n_cols_tmp,
                                     figsize=(20, 8), squeeze=False)
            for h in range(n_heads):
                ax = axes[h // n_cols_tmp, h % n_cols_tmp]
                ax.imshow(aw[-1, h, :elens_l[-1], :elens_l[-1]], aspect="auto")
                ax.grid(False)
                ax.set_xlabel("Input (head%d)" % h)
                ax.set_ylabel("Output (head%d)" % h)
                ax.xaxis.set_major_locator(MaxNLocator(integer=True))
                ax.yaxis.set_major_locator(MaxNLocator(integer=True))

            fig.tight_layout()
            if save_path is not None:
                fig.savefig(os.path.join(save_path, '%s.png' % k), dvi=500)
            plt.close() 
Example #20
Source File: reporter.py    From espnet with Apache License 2.0 5 votes vote down vote up
def _plot_stats(self, keys: Sequence[str], key2: str):
        assert check_argument_types()
        # str is also Sequence[str]
        if isinstance(keys, str):
            raise TypeError(f"Input as [{keys}]")

        import matplotlib

        matplotlib.use("agg")
        import matplotlib.pyplot as plt
        import matplotlib.ticker as ticker

        plt.clf()

        epochs = np.arange(1, self.get_epoch() + 1)
        for key in keys:
            y = [
                self.stats[e][key][key2]
                if e in self.stats
                and key in self.stats[e]
                and key2 in self.stats[e][key]
                else np.nan
                for e in epochs
            ]
            assert len(epochs) == len(y), "Bug?"

            plt.plot(epochs, y, label=key, marker="x")
        plt.legend()
        plt.title(f"epoch vs {key2}")
        # Force integer tick for x-axis
        plt.gca().get_xaxis().set_major_locator(ticker.MaxNLocator(integer=True))
        plt.xlabel("epoch")
        plt.ylabel(key2)
        plt.grid()

        return plt 
Example #21
Source File: microloutputs.py    From pyLIMA with GNU General Public License v3.0 5 votes vote down vote up
def initialize_plot_lightcurve(fit):
    """Initialize the lightcurve plot.

    :param object fit: a fit object. See the microlfits for more details.

    :return: a matplotlib figure  and the corresponding matplotlib axes
    :rtype: matplotlib_figure,matplotlib_axes

    """
    fig_size = [10, 10]
    figure, figure_axes = plt.subplots(2, 1, sharex=True, gridspec_kw={'height_ratios': [3, 1]},
                                       figsize=(fig_size[0], fig_size[1]), dpi=75)
    plt.subplots_adjust(top=0.9, bottom=0.15, left=0.15, right=0.99, wspace=0.2, hspace=0.1)
    figure_axes[0].grid()
    figure_axes[1].grid()
    # fig_size = plt.rcParams["figure.figsize"]
    figure.suptitle(fit.event.name, fontsize=30 * fig_size[0] / len(fit.event.name))

    figure_axes[0].set_ylabel('Mag', fontsize=5 * fig_size[1] * 3 / 4.0)
    figure_axes[0].yaxis.set_major_locator(MaxNLocator(4))
    figure_axes[0].tick_params(axis='y', labelsize=3.5 * fig_size[1] * 3 / 4.0)

    figure_axes[0].text(0.01, 0.96, 'provided by pyLIMA', style='italic', fontsize=10,
                        transform=figure_axes[0].transAxes)

    figure_axes[1].set_xlabel('HJD', fontsize=5 * fig_size[0] * 3 / 4.0)
    figure_axes[1].xaxis.set_major_locator(MaxNLocator(3))
    figure_axes[1].yaxis.set_major_locator(MaxNLocator(4, min_n_ticks=3))

    figure_axes[1].ticklabel_format(useOffset=False, style='plain')
    figure_axes[1].set_ylabel('Residuals', fontsize=5 * fig_size[1] * 2 / 4.0)
    figure_axes[1].tick_params(axis='x', labelsize=3.5 * fig_size[0] * 3 / 4.0)
    figure_axes[1].tick_params(axis='y', labelsize=3.5 * fig_size[1] * 3 / 4.0)

    return figure, figure_axes 
Example #22
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 #23
Source File: plots.py    From ahmia-site with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_figure(x, y1, y2, image_path, metric_str):
    """
    Generate all figures for stats model, normally 4 plots in 2 figures

    :param x A list with dates
    :param y1 A list with integers for bottom line plot
    :param y2 A list with integers for upper line plot
    :param image_path The directory path to store pictures
    :param metric_str: A suffix to plot title, e.g 'Queries'
    """

    # 2 subplots, the axes array is 1-d
    fig, axis = plt.subplots(2, sharex=True)
    fig.set_size_inches(11.4, 5.5)
    x_labels = x  # _select_xticks(x)

    axis[0].set_title("Unique %s" % metric_str)
    axis[0].bar(x, y2, edgecolor="k")  # fill in data
    axis[0].yaxis.set_major_locator(MaxNLocator(integer=True))  # int ylabels
    axis[0].grid(clip_on=True, marker='o', axis='y')  # draw grid lines
    axis[0].set_xticks(x_labels)  # set x-axis label values
    axis[0].set_xticklabels(x_labels)

    axis[1].set_title(metric_str)
    axis[1].bar(x, y1, edgecolor="k")  # fill in data
    axis[1].yaxis.set_major_locator(MaxNLocator(integer=True))  # int ylabels
    axis[1].grid(clip_on=False, marker='o')  # draw grid lines

    # save the figure
    plt.savefig(image_path, bbox_inches='tight', transparent=True) 
Example #24
Source File: visualize.py    From KATE with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def heatmap(data, save_file='heatmap.png'):
    ax = plt.figure().gca()
    ax.yaxis.set_major_locator(MaxNLocator(integer=True))
    ax.yaxis.set_major_locator(MultipleLocator(5))
    plt.pcolor(data, cmap=plt.cm.jet)
    plt.savefig(save_file)
    # plt.show() 
Example #25
Source File: SPY.py    From Stock-Analysis with MIT License 5 votes vote down vote up
def __call__(self, *args, **kwargs):
        return mticker.MaxNLocator.__call__(self, *args, **kwargs)

# at most 5 ticks, pruning the upper and lower so they don't overlap
# with other ticks
#ax2.yaxis.set_major_locator(mticker.MaxNLocator(5, prune='both'))
#ax3.yaxis.set_major_locator(mticker.MaxNLocator(5, prune='both')) 
Example #26
Source File: SPY.py    From Stock-Analysis with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        mticker.MaxNLocator.__init__(self, *args, **kwargs) 
Example #27
Source File: plotting.py    From beat with GNU General Public License v3.0 5 votes vote down vote up
def apply_unified_axis(axs, varnames, unities, axis='x', ntickmarks_max=3,
                       scale_factor=2 / 3):
    for ax, v in zip(axs.ravel('F'), varnames):
        if v in utility.grouped_vars:
            for setname, varrange in unities.items():
                if v in utility.unit_sets[setname]:
                    inc = nice_value(varrange[0] * scale_factor)
                    autos = AutoScaler(
                        inc=inc, snap='on', approx_ticks=ntickmarks_max)
                    if axis == 'x':
                        min, max = ax.get_xlim()
                    elif axis == 'y':
                        min, max = ax.get_ylim()

                    min, max, sinc = autos.make_scale(
                        (min, max), override_mode='min-max')

                    # check physical bounds if passed truncate
                    phys_min, phys_max = physical_bounds[v]
                    if min < phys_min:
                        min = phys_min
                    if max > phys_max:
                        max = phys_max

                    if axis == 'x':
                        ax.set_xlim((min, max))
                    elif axis == 'y':
                        ax.set_ylim((min, max))

                    ticks = num.arange(min, max + inc, inc).tolist()
                    if axis == 'x':
                        ax.xaxis.set_ticks(ticks)
                    elif axis == 'y':
                        ax.yaxis.set_ticks(ticks)
        else:
            ticker = tick.MaxNLocator(nbins=3)
            if axis == 'x':
                ax.get_xaxis().set_major_locator(ticker)
            elif axis == 'y':
                ax.get_yaxis().set_major_locator(ticker) 
Example #28
Source File: grid_finder.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __call__(self, v1, v2):
        if self._factor is not None:
            self.set_bounds(v1*self._factor, v2*self._factor)
            locs = mticker.MaxNLocator.__call__(self)
            return np.array(locs), len(locs), self._factor
        else:
            self.set_bounds(v1, v2)
            locs = mticker.MaxNLocator.__call__(self)
            return np.array(locs), len(locs), None 
Example #29
Source File: grid_finder.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, nbins=10, steps=None,
                 trim=True,
                 integer=False,
                 symmetric=False,
                 prune=None):
        # trim argument has no effect. It has been left for API compatibility
        mticker.MaxNLocator.__init__(self, nbins, steps=steps,
                                     integer=integer,
                                     symmetric=symmetric, prune=prune)
        self.create_dummy_axis()
        self._factor = None 
Example #30
Source File: mpl.py    From neural-pipeline with MIT License 5 votes vote down vote up
def place_plot(self, axis) -> None:
            self._axis = axis

            for n, v in self._prev_values.items():
                self._axis.scatter(v[1], v[0], label=n, c=self._colors[n])

            self._axis.set_ylabel(self._handle)
            self._axis.set_xlabel('epoch')
            self._axis.xaxis.set_major_locator(MaxNLocator(integer=True))
            self._axis.legend()
            plt.grid()