|
| 1 | +""" |
| 2 | +Datetime inputs |
| 3 | +--------------- |
| 4 | +
|
| 5 | +Datetime inputs of the following types are supported in PyGMT: |
| 6 | +
|
| 7 | +- :class:`numpy.datetime64` |
| 8 | +- :class:`pandas.DatetimeIndex` |
| 9 | +- :class:`xarray.DataArray`: datetimes included in a *xarray.DataArray* |
| 10 | +- raw datetime strings in `ISO format <https://en.wikipedia.org/wiki/ISO_8601>`__ (e.g. ``"YYYY-MM-DD"``, ``"YYYY-MM-DDTHH"``, and ``"YYYY-MM-DDTHH:MM:SS"``) |
| 11 | +- Python built-in :class:`datetime.datetime` and :class:`datetime.date` |
| 12 | +
|
| 13 | +We can pass datetime inputs based on one of the types listed above directly to the ``x`` and ``y`` arguments |
| 14 | +of e.g. the :meth:`pygmt.Figure.plot` method: |
| 15 | +
|
| 16 | +The ``region`` argument has to include the :math:`x` and :math:`y` axis limits as *str* in the form |
| 17 | +*date_min/date_max/ymin/ymax*. |
| 18 | +
|
| 19 | +""" |
| 20 | + |
| 21 | +import datetime |
| 22 | + |
| 23 | +import numpy as np |
| 24 | +import pandas as pd |
| 25 | +import pygmt |
| 26 | +import xarray as xr |
| 27 | + |
| 28 | +fig = pygmt.Figure() |
| 29 | + |
| 30 | +# create a basemap with limits of 2010-01-01 to 2020-06-01 on the x axis and |
| 31 | +# 0 to 10 on the y axis |
| 32 | +fig.basemap( |
| 33 | + projection="X15c/5c", region="2010-01-01/2020-06-01/0/10", frame=["WSen", "af"] |
| 34 | +) |
| 35 | + |
| 36 | +# numpy.datetime64 types |
| 37 | +x = np.array(["2010-06-01", "2011-06-01T12", "2012-01-01T12:34:56"], dtype="datetime64") |
| 38 | +y = [1, 2, 3] |
| 39 | +fig.plot(x, y, style="c0.4c", pen="1p", color="red3") |
| 40 | + |
| 41 | +# pandas.DatetimeIndex |
| 42 | +x = pd.date_range("2013", periods=3, freq="YS") |
| 43 | +y = [4, 5, 6] |
| 44 | +fig.plot(x, y, style="t0.4c", pen="1p", color="gold") |
| 45 | + |
| 46 | +# xarray.DataArray |
| 47 | +x = xr.DataArray(data=pd.date_range(start="2015-03", periods=3, freq="QS")) |
| 48 | +y = [7.5, 6, 4.5] |
| 49 | +fig.plot(x, y, style="s0.4c", pen="1p") |
| 50 | + |
| 51 | +# raw datetime strings |
| 52 | +x = ["2016-02-01", "2016-06-04T14", "2016-10-04T00:00:15"] |
| 53 | +y = [7, 8, 9] |
| 54 | +fig.plot(x, y, style="a0.4c", pen="1p", color="dodgerblue") |
| 55 | + |
| 56 | +# the Python built-in datetime and date |
| 57 | +x = [datetime.date(2018, 1, 1), datetime.datetime(2019, 6, 1, 20, 5, 45)] |
| 58 | +y = [6.5, 4.5] |
| 59 | +fig.plot(x, y, style="i0.4c", pen="1p", color="seagreen") |
| 60 | + |
| 61 | +fig.show() |
0 commit comments