Python matplotlib.ticker() Examples

The following are 30 code examples for showing how to use matplotlib.ticker(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module matplotlib , or try the search function .

Example 1
Project: python3_ios   Author: holzschu   File: dates.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, base=1, month=1, day=1, tz=None):
        """
        Mark years that are multiple of base on a given month and day
        (default jan 1).
        """
        DateLocator.__init__(self, tz)
        self.base = ticker._Edge_integer(base, 0)
        self.replaced = {'month':  month,
                         'day':    day,
                         'hour':   0,
                         'minute': 0,
                         'second': 0,
                         }
        if not hasattr(tz, 'localize'):
            # if tz is pytz, we need to do this w/ the localize fcn,
            # otherwise datetime.replace works fine...
            self.replaced['tzinfo'] = tz 
Example 2
Project: postpic   Author: skuschel   File: plotter_matplotlib.py    License: GNU General Public License v3.0 6 votes vote down vote up
def addField1d(ax, field, log10plot=True,
                   xlim=None, ylim=None, scaletight=None):
        field = field.squeeze()
        assert field.dimensions == 1, 'Field needs to be 1 dimensional'
        ax.plot(field.grid, field.matrix, label=field.label)
        ax.xaxis.set_major_formatter(MatplotlibPlotter.axesformatterx)
        ax.yaxis.set_major_formatter(MatplotlibPlotter.axesformattery)
        if log10plot and ((field.matrix < 0).sum() == 0) \
                and any(field.matrix > 0):
            ax.set_yscale('log')  # sets the axis to log scale AND overrides
            # our previously set axesformatter to the default
            # matplotlib.ticker.LogFormatterMathtext.
        MatplotlibPlotter.addaxislabels(ax, field)
        ax.autoscale(tight=scaletight)
        if xlim is not None:
            ax.set_xlim(xlim)
        if ylim is not None:
            ax.set_ylim(ylim)
        return ax 
Example 3
Project: PySimpleGUI   Author: PySimpleGUI   File: 10e PSG (Same Window).py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def set_plot(amp, function):
    global figure_w, figure_h, fig
    fig=plt.figure()
    ax = fig.add_subplot(111)
    x = np.linspace(-np.pi*2, np.pi*2, 100)
    if function == 'sine':
        y= amp*np.sin(x)
        ax.set_title('sin(x)')
    else:
        y=amp*np.cos(x)
        ax.set_title('cos(x)')
    plt.plot(x/np.pi,y)

    
    #centre bottom and left axes to zero

    ax.spines['left'].set_position('zero')
    ax.spines['right'].set_color('none')
    ax.spines['bottom'].set_position('zero')
    ax.spines['top'].set_color('none')

    #Format axes - nicer eh!
    ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%g $\pi$'))

    figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds 
Example 4
def set_plot(amp, function):
    global figure_w, figure_h, fig
    fig=plt.figure()
    ax = fig.add_subplot(111)
    x = np.linspace(-np.pi*2, np.pi*2, 100)
    if function == 'sine':
        y= amp*np.sin(x)
        ax.set_title('sin(x)')
    else:
        y=amp*np.cos(x)
        ax.set_title('cos(x)')
    plt.plot(x/np.pi,y)

    
    #centre bottom and left axes to zero

    ax.spines['left'].set_position('zero')
    ax.spines['right'].set_color('none')
    ax.spines['bottom'].set_position('zero')
    ax.spines['top'].set_color('none')

    #Format axes - nicer eh!
    ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%g $\pi$'))

    figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds 
Example 5
Project: Dense-CoAttention-Network   Author: cvlab-tohoku   File: utils.py    License: MIT License 6 votes vote down vote up
def mask_ques(sen, attn, idx2word):
		"""
		Put attention weights to each word in sentence.
		--------------------
		Arguments:
			sen (LongTensor): encoded sentence.
			attn (FloatTensor): attention weights of each word.
			idx2word (dict): vocabulary.
		"""
		fig, ax = plt.subplots(figsize=(15,15))
		ax.matshow(attn, cmap='bone')
		y = [1]
		x = [1] + [idx2word[i] for i in sen]
		ax.set_yticklabels(y)
		ax.set_xticklabels(x)
		ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
		ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) 
Example 6
Project: coffeegrindsize   Author: jgagneastro   File: dates.py    License: MIT License 6 votes vote down vote up
def __init__(self, base=1, month=1, day=1, tz=None):
        """
        Mark years that are multiple of base on a given month and day
        (default jan 1).
        """
        DateLocator.__init__(self, tz)
        self.base = ticker._Edge_integer(base, 0)
        self.replaced = {'month':  month,
                         'day':    day,
                         'hour':   0,
                         'minute': 0,
                         'second': 0,
                         }
        if not hasattr(tz, 'localize'):
            # if tz is pytz, we need to do this w/ the localize fcn,
            # otherwise datetime.replace works fine...
            self.replaced['tzinfo'] = tz 
Example 7
Project: CogAlg   Author: boris-kz   File: dates.py    License: MIT License 6 votes vote down vote up
def __init__(self, base=1, month=1, day=1, tz=None):
        """
        Mark years that are multiple of base on a given month and day
        (default jan 1).
        """
        DateLocator.__init__(self, tz)
        self.base = ticker._Edge_integer(base, 0)
        self.replaced = {'month':  month,
                         'day':    day,
                         'hour':   0,
                         'minute': 0,
                         'second': 0,
                         }
        if not hasattr(tz, 'localize'):
            # if tz is pytz, we need to do this w/ the localize fcn,
            # otherwise datetime.replace works fine...
            self.replaced['tzinfo'] = tz 
Example 8
Project: PE-HFT-Python   Author: PortfolioEffect   File: plot.py    License: GNU General Public License v3.0 5 votes vote down vote up
def util_plot2d(metric, title='', subtitle = '', line_size=2, title_size=17,date_formatter='%b-%d-%y %H-%M',plot_size=(6,6)):
    if not isinstance(metric, list):
        sys.exit("metric should have class 'list'")
    if not isinstance(title, str):
        sys.exit("title should have class 'str'")
    if not isinstance(subtitle, str):
        sys.exit("subtitle should have class 'str'")
    times=util_timezone(metric[0])

    def format_date(x, pos=None):
        thisind = np.clip(int(x+0.5), 0, N-1)
        return times[thisind].strftime(date_formatter)
    N = len(metric[1])
    ind = np.arange(N)  # the evenly spaced plot indices
    fig, ax = plt.subplots()
    ax.plot(ind, metric[1], lw=line_size)
    ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
    fig.autofmt_xdate()

    
    plt.suptitle(title, y=0.99, fontsize=title_size)
    plt.title(subtitle, fontsize=title_size-5)
    plt.rcParams['figure.figsize'] = plot_size

    plt.grid(True) 
    plt.show() 
Example 9
Project: Computable   Author: ktraunmueller   File: dates.py    License: MIT License 5 votes vote down vote up
def __init__(self, base=1, month=1, day=1, tz=None):
        """
        Mark years that are multiple of base on a given month and day
        (default jan 1).
        """
        DateLocator.__init__(self, tz)
        self.base = ticker.Base(base)
        self.replaced = {'month':  month,
                         'day':    day,
                         'hour':   0,
                         'minute': 0,
                         'second': 0,
                         'tzinfo': tz
                         } 
Example 10
Project: Computable   Author: ktraunmueller   File: dates.py    License: MIT License 5 votes vote down vote up
def __init__(self, interval=1, tz=None):
        """
        *interval* is the interval between each iteration.  For
        example, if ``interval=2``, mark every second microsecond.

        """
        self._interval = interval
        self._wrapped_locator = ticker.MultipleLocator(interval)
        self.tz = tz 
Example 11
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: dates.py    License: MIT License 5 votes vote down vote up
def __init__(self, base=1, month=1, day=1, tz=None):
        """
        Mark years that are multiple of base on a given month and day
        (default jan 1).
        """
        DateLocator.__init__(self, tz)
        self.base = ticker.Base(base)
        self.replaced = {'month':  month,
                         'day':    day,
                         'hour':   0,
                         'minute': 0,
                         'second': 0,
                         'tzinfo': tz
                         } 
Example 12
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: dates.py    License: MIT License 5 votes vote down vote up
def __init__(self, interval=1, tz=None):
        """
        *interval* is the interval between each iteration.  For
        example, if ``interval=2``, mark every second microsecond.

        """
        self._interval = interval
        self._wrapped_locator = ticker.MultipleLocator(interval)
        self.tz = tz 
Example 13
Project: neural-network-animation   Author: miloharper   File: _base.py    License: MIT License 5 votes vote down vote up
def locator_params(self, axis='both', tight=None, **kwargs):
        """
        Control behavior of tick locators.

        Keyword arguments:

        *axis*
            ['x' | 'y' | 'both']  Axis on which to operate;
            default is 'both'.

        *tight*
            [True | False | None] Parameter passed to :meth:`autoscale_view`.
            Default is None, for no change.

        Remaining keyword arguments are passed to directly to the
        :meth:`~matplotlib.ticker.MaxNLocator.set_params` method.

        Typically one might want to reduce the maximum number
        of ticks and use tight bounds when plotting small
        subplots, for example::

            ax.locator_params(tight=True, nbins=4)

        Because the locator is involved in autoscaling,
        :meth:`autoscale_view` is called automatically after
        the parameters are changed.

        This presently works only for the
        :class:`~matplotlib.ticker.MaxNLocator` used
        by default on linear axes, but it may be generalized.
        """
        _x = axis in ['x', 'both']
        _y = axis in ['y', 'both']
        if _x:
            self.xaxis.get_major_locator().set_params(**kwargs)
        if _y:
            self.yaxis.get_major_locator().set_params(**kwargs)
        self.autoscale_view(tight=tight, scalex=_x, scaley=_y) 
Example 14
Project: neural-network-animation   Author: miloharper   File: dates.py    License: MIT License 5 votes vote down vote up
def __init__(self, base=1, month=1, day=1, tz=None):
        """
        Mark years that are multiple of base on a given month and day
        (default jan 1).
        """
        DateLocator.__init__(self, tz)
        self.base = ticker.Base(base)
        self.replaced = {'month':  month,
                         'day':    day,
                         'hour':   0,
                         'minute': 0,
                         'second': 0,
                         'tzinfo': tz
                         } 
Example 15
Project: neural-network-animation   Author: miloharper   File: dates.py    License: MIT License 5 votes vote down vote up
def __init__(self, interval=1, tz=None):
        """
        *interval* is the interval between each iteration.  For
        example, if ``interval=2``, mark every second microsecond.

        """
        self._interval = interval
        self._wrapped_locator = ticker.MultipleLocator(interval)
        self.tz = tz 
Example 16
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _base.py    License: MIT License 5 votes vote down vote up
def locator_params(self, axis='both', tight=None, **kwargs):
        """
        Control behavior of tick locators.

        Parameters
        ----------
        axis : {'both', 'x', 'y'}, optional
            The axis on which to operate.

        tight : bool or None, optional
            Parameter passed to :meth:`autoscale_view`.
            Default is None, for no change.

        Other Parameters
        ----------------
        **kw :
            Remaining keyword arguments are passed to directly to the
            :meth:`~matplotlib.ticker.MaxNLocator.set_params` method.

        Typically one might want to reduce the maximum number
        of ticks and use tight bounds when plotting small
        subplots, for example::

            ax.locator_params(tight=True, nbins=4)

        Because the locator is involved in autoscaling,
        :meth:`autoscale_view` is called automatically after
        the parameters are changed.

        This presently works only for the
        :class:`~matplotlib.ticker.MaxNLocator` used
        by default on linear axes, but it may be generalized.
        """
        _x = axis in ['x', 'both']
        _y = axis in ['y', 'both']
        if _x:
            self.xaxis.get_major_locator().set_params(**kwargs)
        if _y:
            self.yaxis.get_major_locator().set_params(**kwargs)
        self.autoscale_view(tight=tight, scalex=_x, scaley=_y) 
Example 17
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _base.py    License: MIT License 5 votes vote down vote up
def twinx(self):
        """
        Create a twin Axes sharing the xaxis

        Create a new Axes instance with an invisible x-axis and an independent
        y-axis positioned opposite to the original one (i.e. at right). The
        x-axis autoscale setting will be inherited from the original Axes.
        To ensure that the tick marks of both y-axes align, see
        `~matplotlib.ticker.LinearLocator`

        Returns
        -------
        ax_twin : Axes
            The newly created Axes instance

        Notes
        -----
        For those who are 'picking' artists while using twinx, pick
        events are only called for the artists in the top-most axes.
        """
        ax2 = self._make_twin_axes(sharex=self)
        ax2.yaxis.tick_right()
        ax2.yaxis.set_label_position('right')
        ax2.yaxis.set_offset_position('right')
        ax2.set_autoscalex_on(self.get_autoscalex_on())
        self.yaxis.tick_left()
        ax2.xaxis.set_visible(False)
        ax2.patch.set_visible(False)
        return ax2 
Example 18
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _base.py    License: MIT License 5 votes vote down vote up
def twiny(self):
        """
        Create a twin Axes sharing the yaxis

        Create a new Axes instance with an invisible y-axis and an independent
        x-axis positioned opposite to the original one (i.e. at top). The
        y-axis autoscale setting will be inherited from the original Axes.
        To ensure that the tick marks of both x-axes align, see
        `~matplotlib.ticker.LinearLocator`

        Returns
        -------
        ax_twin : Axes
            The newly created Axes instance

        Notes
        -----
        For those who are 'picking' artists while using twiny, pick
        events are only called for the artists in the top-most axes.
        """

        ax2 = self._make_twin_axes(sharey=self)
        ax2.xaxis.tick_top()
        ax2.xaxis.set_label_position('top')
        ax2.set_autoscaley_on(self.get_autoscaley_on())
        self.xaxis.tick_bottom()
        ax2.yaxis.set_visible(False)
        ax2.patch.set_visible(False)
        return ax2 
Example 19
Project: GraphicDesignPatternByPython   Author: Relph1119   File: dates.py    License: MIT License 5 votes vote down vote up
def __init__(self, base=1, month=1, day=1, tz=None):
        """
        Mark years that are multiple of base on a given month and day
        (default jan 1).
        """
        DateLocator.__init__(self, tz)
        self.base = ticker._Edge_integer(base, 0)
        self.replaced = {'month':  month,
                         'day':    day,
                         'hour':   0,
                         'minute': 0,
                         'second': 0,
                         'tzinfo': tz
                         } 
Example 20
Project: GraphicDesignPatternByPython   Author: Relph1119   File: dates.py    License: MIT License 5 votes vote down vote up
def __init__(self, interval=1, tz=None):
        """
        *interval* is the interval between each iteration.  For
        example, if ``interval=2``, mark every second microsecond.

        """
        self._interval = interval
        self._wrapped_locator = ticker.MultipleLocator(interval)
        self.tz = tz 
Example 21
Project: python3_ios   Author: holzschu   File: _base.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def locator_params(self, axis='both', tight=None, **kwargs):
        """
        Control behavior of tick locators.

        Parameters
        ----------
        axis : {'both', 'x', 'y'}, optional
            The axis on which to operate.

        tight : bool or None, optional
            Parameter passed to :meth:`autoscale_view`.
            Default is None, for no change.

        Other Parameters
        ----------------
        **kw :
            Remaining keyword arguments are passed to directly to the
            :meth:`~matplotlib.ticker.MaxNLocator.set_params` method.

        Typically one might want to reduce the maximum number
        of ticks and use tight bounds when plotting small
        subplots, for example::

            ax.locator_params(tight=True, nbins=4)

        Because the locator is involved in autoscaling,
        :meth:`autoscale_view` is called automatically after
        the parameters are changed.

        This presently works only for the
        :class:`~matplotlib.ticker.MaxNLocator` used
        by default on linear axes, but it may be generalized.
        """
        _x = axis in ['x', 'both']
        _y = axis in ['y', 'both']
        if _x:
            self.xaxis.get_major_locator().set_params(**kwargs)
        if _y:
            self.yaxis.get_major_locator().set_params(**kwargs)
        self.autoscale_view(tight=tight, scalex=_x, scaley=_y) 
Example 22
Project: python3_ios   Author: holzschu   File: _base.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def twinx(self):
        """
        Create a twin Axes sharing the xaxis

        Create a new Axes instance with an invisible x-axis and an independent
        y-axis positioned opposite to the original one (i.e. at right). The
        x-axis autoscale setting will be inherited from the original Axes.
        To ensure that the tick marks of both y-axes align, see
        `~matplotlib.ticker.LinearLocator`

        Returns
        -------
        ax_twin : Axes
            The newly created Axes instance

        Notes
        -----
        For those who are 'picking' artists while using twinx, pick
        events are only called for the artists in the top-most axes.
        """
        ax2 = self._make_twin_axes(sharex=self)
        ax2.yaxis.tick_right()
        ax2.yaxis.set_label_position('right')
        ax2.yaxis.set_offset_position('right')
        ax2.set_autoscalex_on(self.get_autoscalex_on())
        self.yaxis.tick_left()
        ax2.xaxis.set_visible(False)
        ax2.patch.set_visible(False)
        return ax2 
Example 23
Project: python3_ios   Author: holzschu   File: _base.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def twiny(self):
        """
        Create a twin Axes sharing the yaxis

        Create a new Axes instance with an invisible y-axis and an independent
        x-axis positioned opposite to the original one (i.e. at top). The
        y-axis autoscale setting will be inherited from the original Axes.
        To ensure that the tick marks of both x-axes align, see
        `~matplotlib.ticker.LinearLocator`

        Returns
        -------
        ax_twin : Axes
            The newly created Axes instance

        Notes
        -----
        For those who are 'picking' artists while using twiny, pick
        events are only called for the artists in the top-most axes.
        """

        ax2 = self._make_twin_axes(sharey=self)
        ax2.xaxis.tick_top()
        ax2.xaxis.set_label_position('top')
        ax2.set_autoscaley_on(self.get_autoscaley_on())
        self.xaxis.tick_bottom()
        ax2.yaxis.set_visible(False)
        ax2.patch.set_visible(False)
        return ax2 
Example 24
Project: python3_ios   Author: holzschu   File: test_ticker.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_majformatter_type():
    fig, ax = plt.subplots()
    with pytest.raises(TypeError):
        ax.xaxis.set_major_formatter(matplotlib.ticker.LogLocator()) 
Example 25
Project: python3_ios   Author: holzschu   File: test_ticker.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_minformatter_type():
    fig, ax = plt.subplots()
    with pytest.raises(TypeError):
        ax.xaxis.set_minor_formatter(matplotlib.ticker.LogLocator()) 
Example 26
Project: python3_ios   Author: holzschu   File: test_ticker.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_minlocator_type():
    fig, ax = plt.subplots()
    with pytest.raises(TypeError):
        ax.xaxis.set_minor_locator(matplotlib.ticker.LogFormatter()) 
Example 27
Project: python3_ios   Author: holzschu   File: dates.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, interval=1, tz=None):
        """
        *interval* is the interval between each iteration.  For
        example, if ``interval=2``, mark every second microsecond.

        """
        self._interval = interval
        self._wrapped_locator = ticker.MultipleLocator(interval)
        self.tz = tz 
Example 28
Project: topmodel   Author: stripe   File: plot_helpers.py    License: MIT License 5 votes vote down vote up
def plot_scores_histogram_log(thresholds, all_counts, xlabel, true_counts=None, ax=None):
    plt.figure()
    # First graph
    if ax is None:
        _, ax = plt.subplots()
    width = (thresholds[1] - thresholds[0]) / 2
    offset = [i + width for i in thresholds]
    if true_counts is not None:
        falses = [i - j for i, j in zip(all_counts, true_counts)]
        plt.bar(offset, falses, width=width,
                log=True, label="False items")
        plt.bar(thresholds, true_counts, width=width,
                log=True, color="purple", label="True items")
    else:
        plt.bar(thresholds, all_counts, width=width,
                log=True, color="purple", label="All items")
    plt.grid(False)
    ax.yaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())
    ax.yaxis.get_major_formatter().set_scientific(False)
    # Write to image
    image_data = StringIO()
    plt.xlim((0.0, 1.0))
    plt.xlabel(xlabel)
    plt.legend(loc='best')
    plt.savefig(image_data, format='svg')
    image_data.seek(0)
    return image_data 
Example 29
Project: neural_sp   Author: hirofumi0810   File: encoder_base.py    License: 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 30
Project: neural_sp   Author: hirofumi0810   File: transformerlm.py    License: Apache License 2.0 5 votes vote down vote up
def plot_attention(self, n_cols=4):
        """Plot attention for each head in all layers."""
        from matplotlib import pyplot as plt
        from matplotlib.ticker import MaxNLocator

        save_path = mkdir_join(self.save_path, 'att_weights')

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

        for lth in range(self.n_layers):
            if not hasattr(self, 'yy_aws_layer%d' % lth):
                continue

            yy_aws = getattr(self, 'yy_aws_layer%d' % lth)

            plt.clf()
            fig, axes = plt.subplots(self.n_heads // n_cols, n_cols, figsize=(20, 8))
            for h in range(self.n_heads):
                if self.n_heads > n_cols:
                    ax = axes[h // n_cols, h % n_cols]
                else:
                    ax = axes[h]
                ax.imshow(yy_aws[-1, h, :, :], 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()
            fig.savefig(os.path.join(save_path, 'layer%d.png' % (lth)), dvi=500)
            plt.close()