nc-time-axis icon indicating copy to clipboard operation
nc-time-axis copied to clipboard

how to best set lim? // allow string in `convert`?

Open mathause opened this issue 7 months ago • 3 comments

✨ Feature Request

Should/ could allow passing a string to convert (of the NetCDFTimeConverter) be beneficial?

Motivation

I want to set the xlim of a nc-time axis. Is there a more convinent way than to pass cftime._cftime.datetime?

It seems I need to do:

import numpy as np
import matplotlib.pyplot as plt
import xarray as xr

data = np.random.randn(100)
time = xr.date_range("2000", "2100", freq="A", calendar="noleap")
da = xr.DataArray(data, coords={"time": time})

f, ax = plt.subplots()

da.plot(ax=ax)
ax.set_xlim(None, da.time.sel(time="2050").item())

It would be nice if we could pass a string - similar as we do with sel in xarray, e.g.:

ax.set_xlim(None, "2050")

Additional context

Click to expand this section...
Please add additional verbose information in this section e.g., references, screenshots, listings etc

mathause avatar Nov 21 '23 15:11 mathause

@spencerkclark Do you have any thoughts on this?

@SciTools/peloton wonders if this is doable at all.

ESadek-MO avatar Nov 22 '23 10:11 ESadek-MO

In principle I think this would be doable, though it would take a little thought to get right. @mathause are you thinking that we would interpret the passed strings independent of whether they corresponded to the start or end of the interval, e.g. "2050" as an end interval would correspond to "2050-01-01T00:00:00", rather than "2050-12-31T23:59:59.999999" as it does in sel?

While matplotlib does not support passing strings for limits of datetime axes on its own (https://github.com/matplotlib/matplotlib/issues/25219), it appears at least pandas has a converter that does. In pandas it seems the answer would be "2050-01-01T00:00:00", which I think makes sense, and is simpler to implement:

fig, ax = plt.subplots(1, 1)

times = pd.date_range("2049", periods=2500)
series = pd.Series(range(2500), index=times)
series.plot(ax=ax)
ax.set_xlim(None, "2050")

image

I'm not sure I have the bandwidth right now to implement this, but I would be open to reviewing a PR.

spencerkclark avatar Dec 09 '23 14:12 spencerkclark

From @SciTools/peloton: is there a way of doing this without introducing further dependencies? Right now nc-time-axis has very few:

https://github.com/SciTools/nc-time-axis/blob/0594c9b053422764b2cc2e1a9c0b4b866159eef3/requirements/py311.yml#L13-L16

... which makes it nice and flexible with Xarray, Iris and others.

trexfeathers avatar Dec 20 '23 10:12 trexfeathers