Skip to content

Incorrect labels returned with custom formatter and locator #9397

Closed

Description

@astrofrog

In the following example I am getting back the wrong labels from ax.xaxis.get_ticklabels:

import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter, MaxNLocator

ax = plt.subplot(1,1,1)

def formatter_func(pos, *args):
    return 'a' if pos == 1 else ''

ax.figure.canvas.draw()
print([tick.get_text() for tick in ax.xaxis.get_ticklabels()])

ax.xaxis.set_major_formatter(FuncFormatter(formatter_func))
ax.xaxis.set_major_locator(MaxNLocator(10, integer=True))

ax.set_xlim(-0.5, 2.5)

ax.figure.canvas.draw()
print([tick.get_text() for tick in ax.xaxis.get_ticklabels()])

This gives:

['0.0', '0.2', '0.4', '0.6', '0.8', '1.0']
['0.0', '', 'a', '', '0.8']

whereas I expected:

['0.0', '0.2', '0.4', '0.6', '0.8', '1.0']
['', '', 'a', '', '']

Activity

  1. afvincent commented on Oct 13, 2017

    @afvincent
    Contributor

    FWIW, if it is not the correct behavior, I was able to reproduce @astrofog's output on Matplotlib 1.5.3 (on GNU/Linux with Python 3.6.2 from conda)...

    Just in case, looking at FuncFormatter docstring, the expected signature is formatter_func(x, pos): @astrofrog is this consistent with what you intended?

  2. anntzer commented on Oct 14, 2017

    @anntzer
    Contributor

    Looks like

    diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py
    index 6cc38bb90..39ac54de1 100644
    --- a/lib/matplotlib/axis.py
    +++ b/lib/matplotlib/axis.py
    @@ -1052,11 +1052,11 @@ class Axis(artist.Artist):
             for tick, loc, label in tick_tups:
                 if tick is None:
                     continue
    -            if not mtransforms.interval_contains(interval_expanded, loc):
    -                continue
                 tick.update_position(loc)
                 tick.set_label1(label)
                 tick.set_label2(label)
    +            if not mtransforms.interval_contains(interval_expanded, loc):
    +                continue
                 ticks_to_draw.append(tick)
     
             return ticks_to_draw
    

    fixes the issue. Basically, the idea is to update the tick labels (and positions) even if they're not going to be drawn (this should be fairly cheap). Feel free to turn the patch into a PR.

    I've argued in a few places that we should just be more careful to actually only have the ticks that are going to be drawn, and not have excess ones on either side.

  3. added this to the milestone on Oct 15, 2017
  4. modified the milestones: , v2.2.0 on Feb 12, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions