.. note::
    :class: sphx-glr-download-link-note

    Click :ref:`here <sphx_glr_download_gallery_subplots_axes_and_figures_axes_margins.py>` to download the full example code
.. rst-class:: sphx-glr-example-title

.. _sphx_glr_gallery_subplots_axes_and_figures_axes_margins.py:


=====================================
Zooming in and out using Axes.margins
=====================================

This example shows how to zoom in and out of a plot using `~.Axes.margins`
instead of `~.Axes.set_xlim` and `~.Axes.set_ylim`.




.. image:: /gallery/subplots_axes_and_figures/images/sphx_glr_axes_margins_001.png
    :class: sphx-glr-single-img





.. code-block:: python


    import numpy as np
    import matplotlib.pyplot as plt


    def f(t):
        return np.exp(-t) * np.cos(2*np.pi*t)


    t1 = np.arange(0.0, 3.0, 0.01)

    ax1 = plt.subplot(212)
    ax1.margins(0.05)           # Default margin is 0.05, value 0 means fit
    ax1.plot(t1, f(t1), 'k')

    ax2 = plt.subplot(221)
    ax2.margins(2, 2)           # Values >0.0 zoom out
    ax2.plot(t1, f(t1), 'r')
    ax2.set_title('Zoomed out')

    ax3 = plt.subplot(222)
    ax3.margins(x=0, y=-0.25)   # Values in (-0.5, 0.0) zooms in to center
    ax3.plot(t1, f(t1), 'g')
    ax3.set_title('Zoomed in')

    plt.show()


.. _sphx_glr_download_gallery_subplots_axes_and_figures_axes_margins.py:


.. only :: html

 .. container:: sphx-glr-footer
    :class: sphx-glr-footer-example



  .. container:: sphx-glr-download

     :download:`Download Python source code: axes_margins.py <axes_margins.py>`



  .. container:: sphx-glr-download

     :download:`Download Jupyter notebook: axes_margins.ipynb <axes_margins.ipynb>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    Keywords: matplotlib code example, codex, python plot, pyplot
    `Gallery generated by Sphinx-Gallery
    <https://sphinx-gallery.readthedocs.io>`_
