proplot-dev / proplot

🎨 A succinct matplotlib wrapper for making beautiful, publication-quality graphics
https://proplot.readthedocs.io
MIT License
1.12k stars 103 forks source link

datetime locator doesn't work with cftime #126

Open bradyrx opened 4 years ago

bradyrx commented 4 years ago

Code sample, a copy-pastable example if possible

import proplot as plot
import numpy as np
import xarray as xr

times = xr.cftime_range('1990', '2000', freq='M')
data = xr.DataArray(np.random.rand(len(times)),
    dims=['time'],
    coords=[times])

f, ax = plot.subplots(aspect=2)

ax.plot(data.time, data)

# ax.format(xlocator='year')
# ax.format(xformatter='concise')

Actual result vs. expected result

The x datetime axis appears by default (with the comments included above), but when using ax.format(xlocator='year') or any locator, the xticks and labeling completely disappear.

When using any formatter (e.g. xformatter='concise') it breaks with the following error:

ValueError: Cannot convert -3652 to a date.  This often happens if non-datetime values are passed to an axis that expects datetime objects.
lukelbd commented 4 years ago

Unfortunately this bug is related to the incompatibility of "cftime" axes with native matplotlib datetime locators, not a proplot bug:

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

times = xr.cftime_range('1990', '2000', freq='M')
data = xr.DataArray(
    np.random.rand(len(times)),
    dims=['time'],
    coords=[times]
)

f, ax = plt.subplots()

ax.plot(data.time, data)
ax.xaxis.set_major_locator(mdates.YearLocator(1))

bug

It appears the default locator for cftime axes is a special nc_time_axis locator:

In [5]: ax.xaxis.get_major_locator()
Out[5]: <nc_time_axis.NetCDFTimeDateLocator at 0x1222c2898>

And unforunately, the nc_time_axis module does not seem to have any other available tick locators. You should request this feature on the nc-time-axis github page.

bradyrx commented 4 years ago

Thanks @lukelbd, I'll move this over there when I get a chance.

bradyrx commented 4 years ago

I'm reopening this based on our discussion at https://github.com/SciTools/nc-time-axis/issues/41. It looks like nc-time-axis is sort of a dead repo. This is on the longer-term list for proplot developments.

lukelbd commented 4 years ago

Works for me

lukelbd commented 4 years ago

After the reorganization, the cftime additions should go in ticker.py. This isn't a priority for me right now, but this is an ideal issue for collaboration if someone else wants to try