Python matplotlib.ticker.AutoMinorLocator() Examples

The following are 23 code examples of matplotlib.ticker.AutoMinorLocator(). 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: _base.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def minorticks_on(self):
        """
        Display minor ticks on the axes.

        Displaying minor ticks may reduce performance; you may turn them off
        using `minorticks_off()` if drawing speed is a problem.
        """
        for ax in (self.xaxis, self.yaxis):
            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()) 
Example #2
Source File: dialog_timeline.py    From RF-Monitor with GNU General Public License v2.0 6 votes vote down vote up
def __setup_plot(self):
        figure = Figure(facecolor='lightgrey')

        self._axes = figure.add_subplot(111)
        self._axes.set_title('Timeline')
        self._axes.set_xlabel('Time')
        self._axes.set_ylabel('Frequency (MHz)')
        self._axes.grid(True)

        locator = AutoDateLocator()
        formatter = AutoDateFormatter(locator)
        self._axes.xaxis.set_major_formatter(formatter)
        self._axes.xaxis.set_major_locator(locator)
        formatter = ScalarFormatter(useOffset=False)
        self._axes.yaxis.set_major_formatter(formatter)
        self._axes.yaxis.set_minor_locator(AutoMinorLocator(10))

        self._canvas = FigureCanvas(self._panelPlot, -1, figure)
        self._canvas.mpl_connect('motion_notify_event', self.__on_motion)

        Legend.__init__(self, self._axes, self._canvas) 
Example #3
Source File: _base.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def minorticks_on(self):
        """
        Display minor ticks on the axes.

        Displaying minor ticks may reduce performance; you may turn them off
        using `minorticks_off()` if drawing speed is a problem.
        """
        for ax in (self.xaxis, self.yaxis):
            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()) 
Example #4
Source File: _base.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def minorticks_on(self):
        """
        Display minor ticks on the axes.

        Displaying minor ticks may reduce performance; you may turn them off
        using `minorticks_off()` if drawing speed is a problem.
        """
        for ax in (self.xaxis, self.yaxis):
            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()) 
Example #5
Source File: _base.py    From CogAlg with MIT License 6 votes vote down vote up
def minorticks_on(self):
        """
        Display minor ticks on the axes.

        Displaying minor ticks may reduce performance; you may turn them off
        using `minorticks_off()` if drawing speed is a problem.
        """
        for ax in (self.xaxis, self.yaxis):
            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()) 
Example #6
Source File: _base.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def minorticks_on(self):
        """
        Display minor ticks on the axes.

        Displaying minor ticks may reduce performance; you may turn them off
        using `minorticks_off()` if drawing speed is a problem.
        """
        for ax in (self.xaxis, self.yaxis):
            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()) 
Example #7
Source File: test_figure.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_autofmt_xdate(which):
    date = ['3 Jan 2013', '4 Jan 2013', '5 Jan 2013', '6 Jan 2013',
            '7 Jan 2013', '8 Jan 2013', '9 Jan 2013', '10 Jan 2013',
            '11 Jan 2013', '12 Jan 2013', '13 Jan 2013', '14 Jan 2013']

    time = ['16:44:00', '16:45:00', '16:46:00', '16:47:00', '16:48:00',
            '16:49:00', '16:51:00', '16:52:00', '16:53:00', '16:55:00',
            '16:56:00', '16:57:00']

    angle = 60
    minors = [1, 2, 3, 4, 5, 6, 7]

    x = mdates.datestr2num(date)
    y = mdates.datestr2num(time)

    fig, ax = plt.subplots()

    ax.plot(x, y)
    ax.yaxis_date()
    ax.xaxis_date()

    ax.xaxis.set_minor_locator(AutoMinorLocator(2))
    ax.xaxis.set_minor_formatter(FixedFormatter(minors))

    fig.autofmt_xdate(0.2, angle, 'right', which)

    if which in ('both', 'major', None):
        for label in fig.axes[0].get_xticklabels(False, 'major'):
            assert int(label.get_rotation()) == angle

    if which in ('both', 'minor'):
        for label in fig.axes[0].get_xticklabels(True, 'minor'):
            assert int(label.get_rotation()) == angle 
Example #8
Source File: test_ticker.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_low_number_of_majorticks(
            self, nb_majorticks, expected_nb_minorticks):
        # This test is related to issue #8804
        fig, ax = plt.subplots()
        xlims = (0, 5)  # easier to test the different code paths
        ax.set_xlim(*xlims)
        ax.set_xticks(np.linspace(xlims[0], xlims[1], nb_majorticks))
        ax.minorticks_on()
        ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())
        assert len(ax.xaxis.get_minorticklocs()) == expected_nb_minorticks 
Example #9
Source File: _base.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def minorticks_on(self):
        'Add autoscaling minor ticks to the axes.'
        for ax in (self.xaxis, self.yaxis):
            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()) 
Example #10
Source File: phonon_bs_plotter.py    From sumo with MIT License 5 votes vote down vote up
def _maketicks(self, ax, units='THz'):
        """Utility method to add tick marks to a band structure."""
        # set y-ticks
        ax.yaxis.set_major_locator(MaxNLocator(6))
        ax.yaxis.set_minor_locator(AutoMinorLocator(2))
        ax.xaxis.set_minor_locator(AutoMinorLocator(2))

        # set x-ticks; only plot the unique tick labels
        ticks = self.get_ticks()
        unique_d = []
        unique_l = []
        if ticks['distance']:
            temp_ticks = list(zip(ticks['distance'], ticks['label']))
            unique_d.append(temp_ticks[0][0])
            unique_l.append(temp_ticks[0][1])
            for i in range(1, len(temp_ticks)):
                if unique_l[-1] != temp_ticks[i][1]:
                    unique_d.append(temp_ticks[i][0])
                    unique_l.append(temp_ticks[i][1])

        logging.info('\nLabel positions:')
        for dist, label in list(zip(unique_d, unique_l)):
            logging.info('\t{:.4f}: {}'.format(dist, label))

        ax.set_xticks(unique_d)
        ax.set_xticklabels(unique_l)
        ax.xaxis.grid(True, ls='-')

        trans_xdata_yaxes = blended_transform_factory(ax.transData,
                                                      ax.transAxes)
        ax.vlines(unique_d, 0, 1,
                  transform=trans_xdata_yaxes,
                  colors=rcParams['grid.color'],
                  linewidth=rcParams['grid.linewidth'])

        # Use a text hyphen instead of a minus sign because some nice fonts
        # like Whitney don't come with a real minus
        labels = {'thz': 'THz', 'cm-1': r'cm$^{\mathrm{-}\mathregular{1}}$',
                  'ev': 'eV', 'mev': 'meV'}
        ax.set_ylabel('Frequency ({0})'.format(labels[units.lower()])) 
Example #11
Source File: test_figure.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_autofmt_xdate(which):
    date = ['3 Jan 2013', '4 Jan 2013', '5 Jan 2013', '6 Jan 2013',
            '7 Jan 2013', '8 Jan 2013', '9 Jan 2013', '10 Jan 2013',
            '11 Jan 2013', '12 Jan 2013', '13 Jan 2013', '14 Jan 2013']

    time = ['16:44:00', '16:45:00', '16:46:00', '16:47:00', '16:48:00',
            '16:49:00', '16:51:00', '16:52:00', '16:53:00', '16:55:00',
            '16:56:00', '16:57:00']

    angle = 60
    minors = [1, 2, 3, 4, 5, 6, 7]

    x = mdates.datestr2num(date)
    y = mdates.datestr2num(time)

    fig, ax = plt.subplots()

    ax.plot(x, y)
    ax.yaxis_date()
    ax.xaxis_date()

    ax.xaxis.set_minor_locator(AutoMinorLocator(2))
    ax.xaxis.set_minor_formatter(FixedFormatter(minors))

    fig.autofmt_xdate(0.2, angle, 'right', which)

    if which in ('both', 'major', None):
        for label in fig.axes[0].get_xticklabels(False, 'major'):
            assert int(label.get_rotation()) == angle

    if which in ('both', 'minor'):
        for label in fig.axes[0].get_xticklabels(True, 'minor'):
            assert int(label.get_rotation()) == angle 
Example #12
Source File: test_ticker.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_low_number_of_majorticks(
            self, nb_majorticks, expected_nb_minorticks):
        # This test is related to issue #8804
        fig, ax = plt.subplots()
        xlims = (0, 5)  # easier to test the different code paths
        ax.set_xlim(*xlims)
        ax.set_xticks(np.linspace(xlims[0], xlims[1], nb_majorticks))
        ax.minorticks_on()
        ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())
        assert len(ax.xaxis.get_minorticklocs()) == expected_nb_minorticks 
Example #13
Source File: _base.py    From ImageFusion with MIT License 5 votes vote down vote up
def minorticks_on(self):
        'Add autoscaling minor ticks to the axes.'
        for ax in (self.xaxis, self.yaxis):
            if ax.get_scale() == 'log':
                s = ax._scale
                ax.set_minor_locator(mticker.LogLocator(s.base, s.subs))
            else:
                ax.set_minor_locator(mticker.AutoMinorLocator()) 
Example #14
Source File: BtPlot.py    From blobtools with GNU General Public License v3.0 5 votes vote down vote up
def set_format_scatterplot(axScatter, **kwargs):
    min_x, max_x = None, None
    min_y, max_y = None, None
    if kwargs['plot'] == 'blobplot':
        min_x, max_x = 0, 1
        major_xticks = MultipleLocator(0.2)
        minor_xticks = AutoMinorLocator(20)
        min_y, max_y = kwargs['min_cov']*0.1, kwargs['max_cov']+100
        axScatter.set_yscale('log')
        axScatter.set_xscale('linear')
        axScatter.xaxis.set_major_locator(major_xticks)
        axScatter.xaxis.set_minor_locator(minor_xticks)
    elif kwargs['plot'] == 'covplot':
        min_x, max_x = kwargs['min_cov']*0.1, kwargs['max_cov']+100
        min_y, max_y = kwargs['min_cov']*0.1, kwargs['max_cov']+100
        axScatter.set_yscale('log')
        axScatter.set_xscale('log')
    else:
        BtLog.error('34' % kwargs['plot'])
    axScatter.set_xlim( (min_x, max_x) )
    axScatter.set_ylim( (min_y, max_y) ) # This sets the max-Coverage so that all libraries + sum are at the same scale
    axScatter.grid(True, which="major", lw=2., color=BGGREY, linestyle='-')
    axScatter.set_axisbelow(True)
    axScatter.xaxis.labelpad = 20
    axScatter.yaxis.labelpad = 20
    axScatter.yaxis.get_major_ticks()[0].label1.set_visible(False)
    axScatter.tick_params(axis='both', which='both', direction='out')
    return axScatter 
Example #15
Source File: statsanalysis.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def plotSeries(key, ymin=None, ymax=None):
    """
    Plot the chosen dataset key for each scanned data file.

    @param key: data set key to use
    @type key: L{str}
    @param ymin: minimum value for y-axis or L{None} for default
    @type ymin: L{int} or L{float}
    @param ymax: maximum value for y-axis or L{None} for default
    @type ymax: L{int} or L{float}
    """

    titles = []
    for title, data in sorted(dataset.items(), key=lambda x: x[0]):
        titles.append(title)
        x, y = zip(*[(k / 3600.0, v[key]) for k, v in sorted(data.items(), key=lambda x: x[0]) if key in v])

        plt.plot(x, y)

    plt.xlabel("Hours")
    plt.ylabel(key)
    plt.xlim(0, 24)
    if ymin is not None:
        plt.ylim(ymin=ymin)
    if ymax is not None:
        plt.ylim(ymax=ymax)
    plt.xticks(
        (1, 4, 7, 10, 13, 16, 19, 22,),
        (18, 21, 0, 3, 6, 9, 12, 15,),
    )
    plt.minorticks_on()
    plt.gca().xaxis.set_minor_locator(AutoMinorLocator(n=3))
    plt.grid(True, "major", "x", alpha=0.5, linewidth=0.5)
    plt.grid(True, "minor", "x", alpha=0.5, linewidth=0.5)
    plt.legend(titles, 'upper left', shadow=True, fancybox=True)
    plt.show() 
Example #16
Source File: train_mnist.py    From models with MIT License 5 votes vote down vote up
def visualize(result, name):
    # (N_samples=5, timesteps=200, types)
    result = np.array(result)
    assert result.shape[2] == 2
    # ax = sns.tsplot(data=result, condition=['OptNet', 'Adam'], linestyle='--')

    def trans(series):
        # (N_samples, timesteps)
        x = np.tile(np.arange(series.shape[1]) + 1,
                    (series.shape[0], 1)).flatten()
        y = series.flatten()
        return {'x': x, 'y': y}
    ax = sns.lineplot(label='OptNet', **trans(result[:, :, 0]))
    ax = sns.lineplot(label='Adam', ax=ax, **trans(result[:, :, 1]))
    ax.lines[-1].set_linestyle('-')
    ax.legend()
    plt.yscale('log'), plt.xlabel('steps')
    plt.ylabel('loss'), plt.title('MNIST')
    plt.ylim(0.09, 3.0)
    plt.xlim(1, result.shape[1])
    plt.grid(which='both', alpha=0.6, color='black', linewidth=0.1,
             linestyle='-')
    ax.tick_params(which='both', direction='in')
    ax.tick_params(which='major', length=8)
    ax.tick_params(which='minor', length=3)
    ax.xaxis.set_minor_locator(AutoMinorLocator(5))

    plt.show()
    plt.savefig(name)
    plt.close() 
Example #17
Source File: test_figure.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_autofmt_xdate(which):
    date = ['3 Jan 2013', '4 Jan 2013', '5 Jan 2013', '6 Jan 2013',
            '7 Jan 2013', '8 Jan 2013', '9 Jan 2013', '10 Jan 2013',
            '11 Jan 2013', '12 Jan 2013', '13 Jan 2013', '14 Jan 2013']

    time = ['16:44:00', '16:45:00', '16:46:00', '16:47:00', '16:48:00',
            '16:49:00', '16:51:00', '16:52:00', '16:53:00', '16:55:00',
            '16:56:00', '16:57:00']

    angle = 60
    minors = [1, 2, 3, 4, 5, 6, 7]

    x = mdates.datestr2num(date)
    y = mdates.datestr2num(time)

    fig, ax = plt.subplots()

    ax.plot(x, y)
    ax.yaxis_date()
    ax.xaxis_date()

    ax.xaxis.set_minor_locator(AutoMinorLocator(2))
    ax.xaxis.set_minor_formatter(FixedFormatter(minors))

    fig.autofmt_xdate(0.2, angle, 'right', which)

    if which in ('both', 'major', None):
        for label in fig.axes[0].get_xticklabels(False, 'major'):
            assert int(label.get_rotation()) == angle

    if which in ('both', 'minor'):
        for label in fig.axes[0].get_xticklabels(True, 'minor'):
            assert int(label.get_rotation()) == angle 
Example #18
Source File: test_ticker.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_low_number_of_majorticks(
            self, nb_majorticks, expected_nb_minorticks):
        # This test is related to issue #8804
        fig, ax = plt.subplots()
        xlims = (0, 5)  # easier to test the different code paths
        ax.set_xlim(*xlims)
        ax.set_xticks(np.linspace(xlims[0], xlims[1], nb_majorticks))
        ax.minorticks_on()
        ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())
        assert len(ax.xaxis.get_minorticklocs()) == expected_nb_minorticks 
Example #19
Source File: colorbar.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def __call__(self):
        vmin = self._colorbar.norm.vmin
        vmax = self._colorbar.norm.vmax
        ticks = ticker.AutoMinorLocator.__call__(self)
        rtol = (vmax - vmin) * 1e-10
        return ticks[(ticks >= vmin - rtol) & (ticks <= vmax + rtol)] 
Example #20
Source File: colorbar.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def __init__(self, colorbar, n=None):
        """
        This ticker needs to know the *colorbar* so that it can access
        its *vmin* and *vmax*.
        """
        self._colorbar = colorbar
        self.ndivs = n
        ticker.AutoMinorLocator.__init__(self, n=None) 
Example #21
Source File: _base.py    From neural-network-animation with MIT License 5 votes vote down vote up
def minorticks_on(self):
        'Add autoscaling minor ticks to the axes.'
        for ax in (self.xaxis, self.yaxis):
            if ax.get_scale() == 'log':
                s = ax._scale
                ax.set_minor_locator(mticker.LogLocator(s.base, s.subs))
            else:
                ax.set_minor_locator(mticker.AutoMinorLocator()) 
Example #22
Source File: plot.py    From spectrum_utils with Apache License 2.0 4 votes vote down vote up
def mirror(spec_top: MsmsSpectrum, spec_bottom: MsmsSpectrum,
           spectrum_kws: Optional[Dict] = None, ax: Optional[plt.Axes] = None)\
        -> plt.Axes:
    """
    Mirror plot two MS/MS spectra.

    Parameters
    ----------
    spec_top : MsmsSpectrum
        The spectrum to be plotted on the top.
    spec_bottom : MsmsSpectrum
        The spectrum to be plotted on the bottom.
    spectrum_kws : Optional[Dict], optional
        Keyword arguments for `plot.spectrum`.
    ax : Optional[plt.Axes], optional
        Axes instance on which to plot the spectrum. If None the current Axes
        instance is used.

    Returns
    -------
    plt.Axes
        The matplotlib Axes instance on which the spectra are plotted.
    """
    if ax is None:
        ax = plt.gca()

    if spectrum_kws is None:
        spectrum_kws = {}
    # Top spectrum.
    spectrum(spec_top, mirror_intensity=False, ax=ax, **spectrum_kws)
    y_max = ax.get_ylim()[1]
    # Mirrored bottom spectrum.
    spectrum(spec_bottom, mirror_intensity=True, ax=ax, **spectrum_kws)
    y_min = ax.get_ylim()[0]
    ax.set_ylim(y_min, y_max)

    ax.axhline(0, color='#9E9E9E', zorder=10)

    # Update axes so that both spectra fit.
    min_mz = max([0, math.floor(spec_top.mz[0] / 100 - 1) * 100,
                  math.floor(spec_bottom.mz[0] / 100 - 1) * 100])
    max_mz = max([math.ceil(spec_top.mz[-1] / 100 + 1) * 100,
                  math.ceil(spec_bottom.mz[-1] / 100 + 1) * 100])
    ax.set_xlim(min_mz, max_mz)
    ax.yaxis.set_major_locator(mticker.AutoLocator())
    ax.yaxis.set_minor_locator(mticker.AutoMinorLocator())
    ax.yaxis.set_major_formatter(mticker.FuncFormatter(
        lambda x, pos: f'{abs(x):.0%}'))

    return ax 
Example #23
Source File: bs_plotter.py    From sumo with MIT License 4 votes vote down vote up
def _maketicks(self, ax, ylabel='Energy (eV)'):
        """Utility method to add tick marks to a band structure."""
        # set y-ticks
        ax.yaxis.set_major_locator(MaxNLocator(6))
        ax.yaxis.set_minor_locator(AutoMinorLocator(2))

        # set x-ticks; only plot the unique tick labels
        ticks = self.get_ticks()
        unique_d = []
        unique_l = []
        if ticks['distance']:
            temp_ticks = list(zip(ticks['distance'], ticks['label']))
            unique_d.append(temp_ticks[0][0])
            unique_l.append(temp_ticks[0][1])
            for i in range(1, len(temp_ticks)):
                # Hide labels marked with @
                if '@' in temp_ticks[i][1]:
                    # If a branch connection, check all parts of label
                    if r'$\mid$' in temp_ticks[i][1]:
                        label_components = temp_ticks[i][1].split(r'$\mid$')
                        good_labels = [l for l in label_components
                                       if l[0] != '@']
                        if len(good_labels) == 0:
                            continue
                        else:
                            temp_ticks[i] = (temp_ticks[i][0],
                                             r'$\mid$'.join(good_labels))
                    # If a single label, check first character
                    elif temp_ticks[i][1][0] == '@':
                        continue

                # Append label to sequence if it is not same as predecessor
                if unique_l[-1] != temp_ticks[i][1]:
                    unique_d.append(temp_ticks[i][0])
                    unique_l.append(temp_ticks[i][1])

        logging.info('Label positions:')
        for dist, label in list(zip(unique_d, unique_l)):
            logging.info('\t{:.4f}: {}'.format(dist, label))

        ax.set_xticks(unique_d)
        ax.set_xticklabels(unique_l)
        ax.xaxis.grid(True, ls='-')
        ax.set_ylabel(ylabel)

        trans_xdata_yaxes = blended_transform_factory(ax.transData,
                                                      ax.transAxes)
        ax.vlines(unique_d, 0, 1,
                  transform=trans_xdata_yaxes,
                  colors=rcParams['grid.color'],
                  linewidth=rcParams['grid.linewidth'],
                  zorder=3)