1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
|
.. _plotting:
Plotting with Matplotlib
========================
Matplotlib_ is a Python plotting library that produces a wide range of plot types
with publication-quality images and support for typesetting mathematical formulas.
Starting with Matplotlib 2.0, **Quantity** instances can be used with matplotlib's
support for units when plotting. To do so, the support must be manually enabled on
a **UnitRegistry**:
.. testsetup:: *
import pint
ureg = pint.UnitRegistry()
.. doctest::
>>> import pint
>>> ureg = pint.UnitRegistry()
>>> ureg.setup_matplotlib()
This support can also be disabled with:
.. doctest::
>>> ureg.setup_matplotlib(False)
This allows plotting quantities with different units:
.. plot::
:include-source: true
import matplotlib.pyplot as plt
import numpy as np
import pint
ureg = pint.UnitRegistry()
ureg.setup_matplotlib(True)
y = np.linspace(0, 30) * ureg.miles
x = np.linspace(0, 5) * ureg.hours
fig, ax = plt.subplots()
ax.plot(x, y, 'tab:blue')
ax.axhline(26400 * ureg.feet, color='tab:red')
ax.axvline(120 * ureg.minutes, color='tab:green')
This also allows controlling the actual plotting units for the x and y axes:
.. plot::
:include-source: true
import matplotlib.pyplot as plt
import numpy as np
import pint
ureg = pint.UnitRegistry()
ureg.setup_matplotlib(True)
y = np.linspace(0, 30) * ureg.miles
x = np.linspace(0, 5) * ureg.hours
fig, ax = plt.subplots()
ax.yaxis.set_units(ureg.inches)
ax.xaxis.set_units(ureg.seconds)
ax.plot(x, y, 'tab:blue')
ax.axhline(26400 * ureg.feet, color='tab:red')
ax.axvline(120 * ureg.minutes, color='tab:green')
Users have the possibility to change the format of the units on the plot:
.. plot::
:include-source: true
import matplotlib.pyplot as plt
import numpy as np
import pint
ureg = pint.UnitRegistry()
ureg.setup_matplotlib(True)
ureg.mpl_formatter = "{:~P}"
y = np.linspace(0, 30) * ureg.miles
x = np.linspace(0, 5) * ureg.hours
fig, ax = plt.subplots()
ax.yaxis.set_units(ureg.inches)
ax.xaxis.set_units(ureg.seconds)
ax.plot(x, y, 'tab:blue')
ax.axhline(26400 * ureg.feet, color='tab:red')
ax.axvline(120 * ureg.minutes, color='tab:green')
For more information, visit the Matplotlib_ home page.
.. _Matplotlib: https://matplotlib.org
|