GenericMappingTools / pygmt

A Python interface for the Generic Mapping Tools.
https://www.pygmt.org
BSD 3-Clause "New" or "Revised" License
747 stars 216 forks source link

Support datetime types in region argument #561

Closed weiji14 closed 4 years ago

weiji14 commented 4 years ago

Description of the desired feature

Support passing in 'datetime' like inputs into the 'region' or '-R' argument in plot.

  • The region argument doesn't work with numpy datetime64 objects, have to convert to a string using np.datetime_as_string in order to set the map frame bounds.

The decorator kwargs_to_strings convert the list [w, e, s, n] to a string w/e/s/n. We need to convert datetime64 object to string internally, but it's not ideal to do the conversion in the decorator. I don't have a good solution now.

Originally posted by @seisman in https://github.com/GenericMappingTools/pygmt/pull/464#issuecomment-636585247

Minimal working example:

import pandas as pd
import pygmt

fig = pygmt.Figure()
fig.plot(x=["2020-06-30"], y=[1], region=[pd.Timestamp("2020-01-01"), pd.Timestamp("2020-12-31"), 0, 2])
fig.show()

The error message is:

GMTCLibError: Module 'plot' failed with status code 71:
plot [ERROR]: Option -R parsing failure. Correct syntax:
plot [ERROR]: Offending option -R2020-01-01

This workaround does work, but it's cumbersome:

fig = pygmt.Figure()
fig.plot(
    x=[pd.Timestamp("2020-06-30")],
    y=[1],
    region=[
        pd.Timestamp("2020-01-01").isoformat(),
        pd.Timestamp("2020-12-31").isoformat(),
        0,
        2,
    ],
    style="a10c",
    frame=True,
)
fig.show()

produces:

Expected plot with star in middle

Are you willing to help implement and maintain this feature? Yes, but where should this code logic go?

seisman commented 4 years ago

Add a check in the kwargs_to_strings decorator?https://github.com/GenericMappingTools/pygmt/blob/2ddbb0e1977af85bf6a6ac63d7cbac9da3d08f05/pygmt/helpers/decorators.py#L244

weiji14 commented 4 years ago

I'm wondering if this functionality is specific to plot only, or if there are other places which can take datetime-like 'region' arguments.

seisman commented 4 years ago

Almost any modules can accept datetime-like region, for example, basemap, histogram, and even grdimage (maybe, but never tried).

weiji14 commented 4 years ago

Ok, the extra 'datetime' check might slow things down by a bit, but since it's only checking for 4 (or 6) items in a list, it should be fine.