2

I'm having a similar problem to this, but that post didn't offer a minimal example. Does anyone have advice?

I sincerely hope the answer isn't "upgrade to matplotlib 3" as the iris package doesn't currently support that and iris is exceedingly useful for what I'm doing.

data.txt:

01-01-2019,00:00:03,334
01-01-2019,00:00:13,314
01-01-2019,00:00:23,295
01-01-2019,00:00:33,280
01-01-2019,00:00:43,310
01-01-2019,00:00:53,300
01-01-2019,00:01:03,310

Code:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as md

data = pd.read_csv(
    "data.txt", infer_datetime_format=True,
    dayfirst=True, parse_dates=[["date", "time"]],
    index_col="date_time",
    names=("date", "time", "wind")
)

ax = plt.axes()
data["wind"].plot(ax=ax)
plt.show()

ax = plt.axes()
data["wind"].plot(ax=ax)
ax.xaxis.set_major_formatter(md.DateFormatter('%Y'))
plt.show()

The first show statement gives this,

From the first show

The second throws this beauty,

--------------------------------------------------------------------------- 
ValueError                                Traceback (most recent call last)
~/bin/conda3/envs/work/lib/python3.6/site-packages/IPython/core/formatters.py
in __call__(self, obj)
    339                 pass
    340             else:
--> 341                 return printer(obj)
    342             # Finally look for special method names
    343             method = get_real_method(obj, self.print_method)

~/bin/conda3/envs/work/lib/python3.6/site-packages/IPython/core/pylabtools.py
in <lambda>(fig)
    242 
    243     if 'png' in formats:
--> 244         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    245     if 'retina' in formats or 'png2x' in formats:
    246         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

~/bin/conda3/envs/work/lib/python3.6/site-packages/IPython/core/pylabtools.py
in print_figure(fig, fmt, bbox_inches, **kwargs)
    126 
    127     bytes_io = BytesIO()
--> 128     fig.canvas.print_figure(bytes_io, **kw)
    129     data = bytes_io.getvalue()
    130     if fmt == 'svg':

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/backend_bases.py
in print_figure(self, filename, dpi, facecolor, edgecolor,
orientation, format, **kwargs)    2210                    
orientation=orientation,    2211                     dryrun=True,
-> 2212                     **kwargs)    2213                 renderer = self.figure._cachedRenderer    2214                 bbox_inches = self.figure.get_tightbbox(renderer)

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py
in print_png(self, filename_or_obj, *args, **kwargs)
    515 
    516     def print_png(self, filename_or_obj, *args, **kwargs):
--> 517         FigureCanvasAgg.draw(self)
    518         renderer = self.get_renderer()
    519         original_dpi = renderer.dpi

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py
in draw(self)
    435             # if toolbar:
    436             #     toolbar.set_cursor(cursors.WAIT)
--> 437             self.figure.draw(self.renderer)
    438             # A GUI class may be need to update a window using this draw, so
    439             # don't forget to call the superclass.

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/artist.py
in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/figure.py
in draw(self, renderer)    1491     1492            
mimage._draw_list_compositing_images(
-> 1493                 renderer, self, artists, self.suppressComposite)    1494     1495            
renderer.close_group('figure')

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/image.py
in _draw_list_compositing_images(renderer, parent, artists,
suppress_composite)
    139     if not_composite or not has_images:
    140         for a in artists:
--> 141             a.draw(renderer)
    142     else:
    143         # Composite any adjacent images together

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/artist.py
in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/axes/_base.py
in draw(self, renderer, inframe)    2633            
renderer.stop_rasterizing()    2634 
-> 2635         mimage._draw_list_compositing_images(renderer, self, artists)    2636     2637         renderer.close_group('axes')

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/image.py
in _draw_list_compositing_images(renderer, parent, artists,
suppress_composite)
    139     if not_composite or not has_images:
    140         for a in artists:
--> 141             a.draw(renderer)
    142     else:
    143         # Composite any adjacent images together

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/artist.py
in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)    1188        
renderer.open_group(__name__)    1189 
-> 1190         ticks_to_draw = self._update_ticks(renderer)    1191         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
1192                                                                
renderer)

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/axis.py in _update_ticks(self, renderer)    1026     1027         interval =
self.get_view_interval()
-> 1028         tick_tups = list(self.iter_ticks())  # iter_ticks calls the locator    1029         if self._smart_bounds and tick_tups:
1030             # handle inverted limits

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/axis.py in iter_ticks(self)
    973         self.major.formatter.set_locs(majorLocs)
    974         majorLabels = [self.major.formatter(val, i)
--> 975                        for i, val in enumerate(majorLocs)]
    976 
    977         minorLocs = self.minor.locator()

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/axis.py in <listcomp>(.0)
    973         self.major.formatter.set_locs(majorLocs)
    974         majorLabels = [self.major.formatter(val, i)
--> 975                        for i, val in enumerate(majorLocs)]
    976 
    977         minorLocs = self.minor.locator()

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/dates.py
in __call__(self, x, pos)
    632                              'you have not informed the axis that it is '
    633                              'plotting dates, e.g., with ax.xaxis_date()')
--> 634         dt = num2date(x, self.tz)
    635         return self.strftime(dt, self.fmt)
    636 

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/dates.py
in num2date(x, tz)
    520         tz = _get_rc_timezone()
    521     if not cbook.iterable(x):
--> 522         return _from_ordinalf(x, tz)
    523     else:
    524         x = np.asarray(x)

~/bin/conda3/envs/work/lib/python3.6/site-packages/matplotlib/dates.py
in _from_ordinalf(x, tz)
    320                          'non-datetime values are passed to an axis that '
    321                          'expects datetime objects.'.format(ix))
--> 322     dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
    323 
    324     # Since the input date `x` float is unable to preserve microsecond

ValueError: year 4233628 is out of range
joanis
  • 10,635
  • 14
  • 30
  • 40
  • 1
    If you have a special requirement concerning versions, you should state which versions of python, pandas and matplotlib you are bound to. Concerning the actual probem: You cannot in general use matplotlib formatters for pandas datetime axes. You can plot your data with matplotlib, or at least use the pandas `x_compat=True` option. Also note that setting the formatter alone, is rarely useful, as it might give you minutely ticks all with the same year written in the label. – ImportanceOfBeingErnest Feb 22 '19 at 18:33
  • x_compat=True solved the problem for me – yl_low Dec 16 '19 at 03:45

0 Answers0