<commit_before>.. _quantity:

Quantity
********

.. |quantity| replace:: :class:`~astropy.units.Quantity`

The |quantity| object is meant to represent a value that has some unit
associated with the number.

Creating Quantity instances
===========================

|quantity| objects are normally created through multiplication with
:class:`~astropy.units.Unit` objects. For example, to create a |quantity|
to represent 15 m/s:

    >>> import astropy.units as u
    >>> 15 * u.m / u.s  # doctest: +FLOAT_CMP
    <Quantity 15. m / s>

This extends as expected to division by a unit, or using Numpy arrays or Python
sequences:

    >>> 1.25 / u.s
    <Quantity 1.25 1 / s>
    >>> [1, 2, 3] * u.m  # doctest: +FLOAT_CMP
    <Quantity [1., 2., 3.] m>
    >>> import numpy as np
    >>> np.array([1, 2, 3]) * u.m  # doctest: +FLOAT_CMP
    <Quantity [1., 2., 3.] m>

You can also create instances using the |quantity| constructor directly, by
specifying a value and unit:

    >>> u.Quantity(15, u.m / u.s)  # doctest: +FLOAT_CMP
    <Quantity 15. m / s>

The constructor gives a few more options.  In particular, it allows one to
merge sequences of |quantity| objects (as long as all of their units are
equivalent), and to parse simple strings (which may help, e.g., to parse
configuration files, etc.):

    >>> qlst = [60 * u.s, 1 * u.min]
    >>> u.Quantity(qlst, u.minute)  # doctest: +FLOAT_CMP
    <Quantity [1.,  1.] min>
    >>> u.Quantity('15 m/s')  # doctest: +FLOAT_CMP
    <Quantity 15. m / s>

The current unit and value can be accessed via the
`~astropy.units.quantity.Quantity.unit` and
`~astropy.units.quantity.Quantity.value` attributes:

    >>> q = 2.5 * u.m / u.s
    >>> q.unit
    Unit("m / s")
    >>> q.value
    2.5

.. note:: |quantity| objects are converted to float by default.  Furthermore,
	  any data passed in are copied, which for large arrays may not be
	  optimal.  As discussed :ref:`further below
	  <astropy-units-quantity-no-copy>`.  one can instead obtain a
	  `~numpy.ndarray.view` by passing ``copy=False`` to |quantity| or use
	  the ``<<`` operator.

Converting to different units
=============================

|quantity| objects can be converted to different units using the
:meth:`~astropy.units.quantity.Quantity.to` method:

    >>> q = 2.3 * u.m / u.s
    >>> q.to(u.km / u.h)  # doctest: +FLOAT_CMP
    <Quantity 8.28 km / h>

For convenience, the `~astropy.units.quantity.Quantity.si` and
`~astropy.units.quantity.Quantity.cgs` attributes can be used to
convert the |quantity| to base S.I. or c.g.s units:

    >>> q = 2.4 * u.m / u.s
    >>> q.si  # doctest: +FLOAT_CMP
    <Quantity 2.4 m / s>
    >>> q.cgs  # doctest: +FLOAT_CMP
    <Quantity 240. cm / s>

If you want the value of the quantity in a different unit, you can use
:meth:`~astropy.units.Quantity.to_value` as a short-cut:

    >>> q = 2.5 * u.m
    >>> q.to_value(u.cm)
    250.0

.. note:: You could get the value in ``cm`` also using ``q.to(u.cm).value``.
          The difference is that :meth:`~astropy.units.Quantity.to_value` does
          no conversion if the unit is already the correct one, instead just
          returning an :meth:`~numpy.ndarray.view` of the data (just as if you
          had done ``q.value``).  In contrast,
          :meth:`~astropy.units.Quantity.to` always returns a copy (which also
          means it is slower for the case where no conversion is necessary).
          As discussed :ref:`further below <astropy-units-quantity-no-copy>`,
          one can avoid the copy if the unit is already correct by using the
          ``<<`` operator.

Comparing quantities
====================

|quantity| objects can be compared as follows:

    >>> from astropy import units as u
    >>> u.allclose([1, 2] * u.m, [100, 200] * u.cm)
    True
    >>> u.isclose([1, 2] * u.m, [100, 20] * u.cm)  # doctest: +SKIP
    array([ True, False])

.. _plotting-quantities:

Plotting quantities
===================

|quantity| objects can be conveniently plotted using matplotlib.  This
feature needs to be explicitly turned on:

.. doctest-requires:: matplotlib

    >>> from astropy.visualization import quantity_support
    >>> quantity_support()  # doctest: +IGNORE_OUTPUT
    <astropy.visualization.units.MplQuantityConverter ...>

Then |quantity| objects can be passed to matplotlib plotting
functions.  The axis labels are automatically labeled with the unit of
the quantity:

.. doctest-requires:: matplotlib

    >>> from matplotlib import pyplot as plt
    >>> plt.figure(figsize=(5,3))
    <...>
    >>> plt.plot([1, 2, 3] * u.m)
    [...]

.. plot::

    from astropy import units as u
    from astropy.visualization import quantity_support
    quantity_support()
    from matplotlib import pyplot as plt
    plt.figure(figsize=(5,3))
    plt.plot([1, 2, 3] * u.m)

Quantities are automatically converted to the first unit set on a
particular axis, so in the following, the y-axis remains in ``m`` even
though the second line is given in ``cm``:

.. doctest-requires:: matplotlib

    >>> plt.plot([1, 2, 3] * u.cm)
    [...]

.. plot::

    from astropy import units as u
    from astropy.visualization import quantity_support
    quantity_support()
    from matplotlib import pyplot as plt
    plt.figure(figsize=(5,3))
    plt.plot([1, 2, 3] * u.m)
    plt.plot([1, 2, 3] * u.cm)

Plotting a quantity with an incompatible unit will raise an exception:

.. doctest-requires:: matplotlib

    >>> plt.plot([1, 2, 3] * u.kg)  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    ...
    UnitConversionError: 'kg' (mass) and 'm' (length) are not convertible
    >>> plt.clf()

To make sure unit support is turned off afterward, you can use
`~astropy.visualization.quantity_support` with a ``with`` statement:

.. doctest-requires:: matplotlib

    >>> from astropy.visualization import quantity_support
    >>> from matplotlib import pyplot as plt
    >>> with quantity_support():
    ...     plt.figure(figsize=(5,3))
    ...     plt.plot([1, 2, 3] * u.m)
    <...>
    [...]
<commit_msg>Remove doctest that raises exception in plot example<commit_after>.. _quantity:

Quantity
********

.. |quantity| replace:: :class:`~astropy.units.Quantity`

The |quantity| object is meant to represent a value that has some unit
associated with the number.

Creating Quantity instances
===========================

|quantity| objects are normally created through multiplication with
:class:`~astropy.units.Unit` objects. For example, to create a |quantity|
to represent 15 m/s:

    >>> import astropy.units as u
    >>> 15 * u.m / u.s  # doctest: +FLOAT_CMP
    <Quantity 15. m / s>

This extends as expected to division by a unit, or using Numpy arrays or Python
sequences:

    >>> 1.25 / u.s
    <Quantity 1.25 1 / s>
    >>> [1, 2, 3] * u.m  # doctest: +FLOAT_CMP
    <Quantity [1., 2., 3.] m>
    >>> import numpy as np
    >>> np.array([1, 2, 3]) * u.m  # doctest: +FLOAT_CMP
    <Quantity [1., 2., 3.] m>

You can also create instances using the |quantity| constructor directly, by
specifying a value and unit:

    >>> u.Quantity(15, u.m / u.s)  # doctest: +FLOAT_CMP
    <Quantity 15. m / s>

The constructor gives a few more options.  In particular, it allows one to
merge sequences of |quantity| objects (as long as all of their units are
equivalent), and to parse simple strings (which may help, e.g., to parse
configuration files, etc.):

    >>> qlst = [60 * u.s, 1 * u.min]
    >>> u.Quantity(qlst, u.minute)  # doctest: +FLOAT_CMP
    <Quantity [1.,  1.] min>
    >>> u.Quantity('15 m/s')  # doctest: +FLOAT_CMP
    <Quantity 15. m / s>

The current unit and value can be accessed via the
`~astropy.units.quantity.Quantity.unit` and
`~astropy.units.quantity.Quantity.value` attributes:

    >>> q = 2.5 * u.m / u.s
    >>> q.unit
    Unit("m / s")
    >>> q.value
    2.5

.. note:: |quantity| objects are converted to float by default.  Furthermore,
	  any data passed in are copied, which for large arrays may not be
	  optimal.  As discussed :ref:`further below
	  <astropy-units-quantity-no-copy>`.  one can instead obtain a
	  `~numpy.ndarray.view` by passing ``copy=False`` to |quantity| or use
	  the ``<<`` operator.

Converting to different units
=============================

|quantity| objects can be converted to different units using the
:meth:`~astropy.units.quantity.Quantity.to` method:

    >>> q = 2.3 * u.m / u.s
    >>> q.to(u.km / u.h)  # doctest: +FLOAT_CMP
    <Quantity 8.28 km / h>

For convenience, the `~astropy.units.quantity.Quantity.si` and
`~astropy.units.quantity.Quantity.cgs` attributes can be used to
convert the |quantity| to base S.I. or c.g.s units:

    >>> q = 2.4 * u.m / u.s
    >>> q.si  # doctest: +FLOAT_CMP
    <Quantity 2.4 m / s>
    >>> q.cgs  # doctest: +FLOAT_CMP
    <Quantity 240. cm / s>

If you want the value of the quantity in a different unit, you can use
:meth:`~astropy.units.Quantity.to_value` as a short-cut:

    >>> q = 2.5 * u.m
    >>> q.to_value(u.cm)
    250.0

.. note:: You could get the value in ``cm`` also using ``q.to(u.cm).value``.
          The difference is that :meth:`~astropy.units.Quantity.to_value` does
          no conversion if the unit is already the correct one, instead just
          returning an :meth:`~numpy.ndarray.view` of the data (just as if you
          had done ``q.value``).  In contrast,
          :meth:`~astropy.units.Quantity.to` always returns a copy (which also
          means it is slower for the case where no conversion is necessary).
          As discussed :ref:`further below <astropy-units-quantity-no-copy>`,
          one can avoid the copy if the unit is already correct by using the
          ``<<`` operator.

Comparing quantities
====================

|quantity| objects can be compared as follows:

    >>> from astropy import units as u
    >>> u.allclose([1, 2] * u.m, [100, 200] * u.cm)
    True
    >>> u.isclose([1, 2] * u.m, [100, 20] * u.cm)  # doctest: +SKIP
    array([ True, False])

.. _plotting-quantities:

Plotting quantities
===================

|quantity| objects can be conveniently plotted using matplotlib.  This
feature needs to be explicitly turned on:

.. doctest-requires:: matplotlib

    >>> from astropy.visualization import quantity_support
    >>> quantity_support()  # doctest: +IGNORE_OUTPUT
    <astropy.visualization.units.MplQuantityConverter ...>

Then |quantity| objects can be passed to matplotlib plotting
functions.  The axis labels are automatically labeled with the unit of
the quantity:

.. doctest-requires:: matplotlib

    >>> from matplotlib import pyplot as plt
    >>> plt.figure(figsize=(5,3))
    <...>
    >>> plt.plot([1, 2, 3] * u.m)
    [...]

.. plot::

    from astropy import units as u
    from astropy.visualization import quantity_support
    quantity_support()
    from matplotlib import pyplot as plt
    plt.figure(figsize=(5,3))
    plt.plot([1, 2, 3] * u.m)

Quantities are automatically converted to the first unit set on a
particular axis, so in the following, the y-axis remains in ``m`` even
though the second line is given in ``cm``:

.. doctest-requires:: matplotlib

    >>> plt.plot([1, 2, 3] * u.cm)
    [...]

.. plot::

    from astropy import units as u
    from astropy.visualization import quantity_support
    quantity_support()
    from matplotlib import pyplot as plt
    plt.figure(figsize=(5,3))
    plt.plot([1, 2, 3] * u.m)
    plt.plot([1, 2, 3] * u.cm)

Plotting a quantity with an incompatible unit will raise an exception.
For example, calling ``plt.plot([1, 2, 3] * u.kg)`` (mass unit) to overplot
on the plot above that is displaying length units.

To make sure unit support is turned off afterward, you can use
`~astropy.visualization.quantity_support` with a ``with`` statement:

.. doctest-requires:: matplotlib

    >>> from astropy.visualization import quantity_support
    >>> from matplotlib import pyplot as plt
    >>> with quantity_support():
    ...     plt.figure(figsize=(5,3))
    ...     plt.plot([1, 2, 3] * u.m)
    <...>
    [...]

{'fraction_non_alphanumeric': 0.14473246925889, 'fraction_numerical': 0.017281488866733134, 'mean_word_length': 3.0365526492287054, 'pattern_counts': {'":': 0, '<': 41, '<?xml version=': 0, '>': 231, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6308366', 'n_tokens_mistral': 4167, 'n_tokens_neox': 3816, 'n_words': 1380}