pandas: BUG: get UserWarning about FixedFormatter/FixedLocator in series.plot()

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • (optional) I have confirmed this bug exists on the master branch of pandas.

Code Sample, a copy-pastable example

pd.Series({"20190102": 10, "20190103": 10}).plot()

Problem description

Got a UserWarning:

/home/.../miniconda3/lib/python3.8/site-packages/pandas/plotting/_matplotlib/core.py:1192: UserWarning: FixedFormatter should only be used together with FixedLocator

And to catch the Warning:

import warnings
with warnings.catch_warnings():
    warnings.filterwarnings("error")
    pd.Series({"20190102": 10, "20190103": 10}).plot()

Got

---------------------------------------------------------------------------
UserWarning                               Traceback (most recent call last)
<ipython-input-5-4339a8efd56e> in <module>
      2 with warnings.catch_warnings():
      3     warnings.filterwarnings("error")
----> 4     pd.Series({"20190102": 10, "20190103": 10}).plot()

~/miniconda3/lib/python3.8/site-packages/pandas/plotting/_core.py in __call__(self, *args, **kwargs)
    845                     data.columns = label_name
    846 
--> 847         return plot_backend.plot(data, kind=kind, **kwargs)
    848 
    849     __call__.__doc__ = __doc__

~/miniconda3/lib/python3.8/site-packages/pandas/plotting/_matplotlib/__init__.py in plot(data, kind, **kwargs)
     59             kwargs["ax"] = getattr(ax, "left_ax", ax)
     60     plot_obj = PLOT_CLASSES[kind](data, **kwargs)
---> 61     plot_obj.generate()
     62     plot_obj.draw()
     63     return plot_obj.result

~/miniconda3/lib/python3.8/site-packages/pandas/plotting/_matplotlib/core.py in generate(self)
    268         for ax in self.axes:
    269             self._post_plot_logic_common(ax, self.data)
--> 270             self._post_plot_logic(ax, self.data)
    271 
    272     def _args_adjust(self):

~/miniconda3/lib/python3.8/site-packages/pandas/plotting/_matplotlib/core.py in _post_plot_logic(self, ax, data)
   1190             xticks = ax.get_xticks()
   1191             xticklabels = [get_label(x) for x in xticks]
-> 1192             ax.set_xticklabels(xticklabels)
   1193             ax.xaxis.set_major_locator(FixedLocator(xticks))
   1194 

~/miniconda3/lib/python3.8/site-packages/matplotlib/axes/_base.py in wrapper(self, *args, **kwargs)
     61 
     62         def wrapper(self, *args, **kwargs):
---> 63             return get_method(self)(*args, **kwargs)
     64 
     65         wrapper.__module__ = owner.__module__

~/miniconda3/lib/python3.8/site-packages/matplotlib/cbook/deprecation.py in wrapper(*args, **kwargs)
    449                 "parameter will become keyword-only %(removal)s.",
    450                 name=name, obj_type=f"parameter of {func.__name__}()")
--> 451         return func(*args, **kwargs)
    452 
    453     return wrapper

~/miniconda3/lib/python3.8/site-packages/matplotlib/axis.py in _set_ticklabels(self, labels, fontdict, minor, **kwargs)
   1791         if fontdict is not None:
   1792             kwargs.update(fontdict)
-> 1793         return self.set_ticklabels(labels, minor=minor, **kwargs)
   1794 
   1795     @cbook._make_keyword_only("3.2", "minor")

~/miniconda3/lib/python3.8/site-packages/matplotlib/axis.py in set_ticklabels(self, ticklabels, minor, **kwargs)
   1728             ticks = self.get_minor_ticks(len(locs))
   1729         else:
-> 1730             self.set_major_formatter(formatter)
   1731             locs = self.get_majorticklocs()
   1732             ticks = self.get_major_ticks(len(locs))

~/miniconda3/lib/python3.8/site-packages/matplotlib/axis.py in set_major_formatter(self, formatter)
   1589         formatter : `~matplotlib.ticker.Formatter`, ``str``, or function
   1590         """
-> 1591         self._set_formatter(formatter, self.major)
   1592 
   1593     def set_minor_formatter(self, formatter):

~/miniconda3/lib/python3.8/site-packages/matplotlib/axis.py in _set_formatter(self, formatter, level)
   1619                 and len(formatter.seq) > 0
   1620                 and not isinstance(level.locator, mticker.FixedLocator)):
-> 1621             cbook._warn_external('FixedFormatter should only be used together '
   1622                                  'with FixedLocator')
   1623 

~/miniconda3/lib/python3.8/site-packages/matplotlib/cbook/__init__.py in _warn_external(message, category)
   2088             break
   2089         frame = frame.f_back
-> 2090     warnings.warn(message, category, stacklevel)
   2091 
   2092 

UserWarning: FixedFormatter should only be used together with FixedLocator

Output of pd.show_versions()

INSTALLED VERSIONS

commit : None python : 3.8.5.final.0 python-bits : 64 OS : Linux OS-release : 4.19.104-microsoft-standard machine : x86_64 processor : x86_64 byteorder : little LC_ALL : None LANG : C.UTF-8 LOCALE : en_US.UTF-8

pandas : 1.0.5 numpy : 1.19.1 pytz : 2020.1 dateutil : 2.8.1 pip : 20.2.1 setuptools : 49.3.1.post20200810 Cython : None pytest : 6.0.1 hypothesis : None sphinx : 3.2.0 blosc : None feather : None xlsxwriter : None lxml.etree : 4.5.2 html5lib : None pymysql : 0.10.0 psycopg2 : None jinja2 : 2.11.2 IPython : 7.17.0 pandas_datareader: None bs4 : 4.9.1 bottleneck : None fastparquet : None gcsfs : None lxml.etree : 4.5.2 matplotlib : 3.3.0 numexpr : 2.7.1 odfpy : None openpyxl : 3.0.4 pandas_gbq : None pyarrow : 1.0.0 pytables : None pytest : 6.0.1 pyxlsb : None s3fs : None scipy : 1.5.2 sqlalchemy : 1.3.18 tables : 3.6.1 tabulate : 0.8.7 xarray : None xlrd : 1.2.0 xlwt : None xlsxwriter : None numba : None

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 18 (6 by maintainers)

Commits related to this issue

Most upvoted comments

I’m using 3.3.1 and set_major_foarmatter but still getting a UserWarning: FixedFormatter should only be used together with FixedLocator

Am I missing something?

import matplotlib.pyplot as plt
from matplotlib.ticker import FixedLocator, FixedFormatter

fig, ax = plt.subplots()
ax.scatter(0.5, 0.5)

x_formatter = FixedFormatter(['0', r'$T/2$', r'$T$'])
x_locator = FixedLocator([0, 0.5, 1])
ax.xaxis.set_major_formatter(x_formatter)
ax.xaxis.set_major_locator(x_locator)

ax.set_xlim(0, 1)

Switch those two statements would fix the warning.

ax.xaxis.set_major_locator(x_locator)
ax.xaxis.set_major_formatter(x_formatter)

You did not provide the data in your example, so I cannot reproduce it, but it seems to me that the problem originates with the x axis.

  • Instead of
ax.set_xticklabels(med2008_sub.index, rotation=45, ha="right", rotation_mode="anchor")
  • Try first:
ax.figure.canvas.draw()
ax.xaxis.set_major_formatter('{x:0.0f}')
ax.tick_params(axis='x',which='major', rotation=45)
  • Then:
ax.figure.canvas.draw()
ax.tick_params(axis='x',which='major', rotation=45)

#35946 was a relatively small change. maybe could be backported.

The problem comes from Matplotlib: I can reproduce the problem without using Pandas.

  • Info:
Matplotlib: 3.3.1
Python: 3.7.6 | packaged by conda-forge | (default, Jun  1 2020, 18:11:50) [MSC v.1916 64 bit (AMD64)]
Platform: win32
  • Test data:
np.random.seed(123)
x = np.array(range(10))
y = np.random.random_sample(10)*4
  • Plot triggering the warning:
fig, ax = plt.subplots(1, figsize=(8,5))
ax.bar(x, y);

title1 = "UserWarning: FixedFormatter should only be used together with FixedLocator"
labels = [str(np.round(item.get_position()[1], 3))
              for item in ax.get_yticklabels()]

ax.set(xlim=None,
        xticks=[],
        xlabel='',
        yticklabels=labels,
        ylabel='Series values',
        title=title1)

plt.show();

user_warn_on

  • Amended code that removes the warning:
fig, ax = plt.subplots(1, figsize=(8,5))
ax.bar(x, y);

title2 = "No UserWarning using set_major_formatter"
ax.yaxis.set_major_formatter('{x:.1f}')
ax.set(xlim=None,
       xticks=[],
       xlabel='',
       ylabel='Series values',
       title=title2
      )
plt.show();

user_warn_off