You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Setting xticklabels causes warning related to FixedFormatter #18848
<ipython-input-3-52a3699e4278>:5: UserWarning: FixedFormatter should only be used together with FixedLocator
ax.set_xticklabels(['0', r'$T/2$', r'$T$'])
Also, If you do set the tick locations, you have to do it first (I revised my code sample to show this). Yes, it's cleaner to set the locations first and then the labels, but I don't think it should be a warning. As long as the locator and labels have both been set by the time the plot is drawn, it should be OK.
The problem is when people zoom or otherwise change the view, and we continue to use an AutoLocator, the labels will often end up applied to the wrong ticks. By encouraging you to manually specify the ticks we help you avoid that possibility.
Thanks, @jklymak: now I understand why the warning was included. However, I'm assuming there is a lot of code out there - the one I use the most on a day-to-day basis included - that only plots "fixed" charts. Therefore, having to add a line of code using FixedLocator (if what I want is just to format the existing labels), would make the conde unnecessarily polluted, no? Maybe the potential issue you describe should be included somewhere on matplotlib's documentation?
Reacted by VongCanhChi, Fanchen Bao, Mahdi Aslani, Wenyuan Wu, Wilhelm Wermelin, Shelly-Lee, BitnaKeum, Liam Marriott, Sebastián Guzmán, Sheshadri K R and 1 more
Side note: I'm tempted to modify set_ticks()
from set_ticks(ticks, *, minor=False)
to set_ticks(ticks, *, labels=None, minor=False).
That would allow to set_ticks([1, 2, 3], labels=['$\pi$', '$2\pi$', '$3\pi$']) and would exactly prevent this problem. A bit hesitant because that'd break the symmetry between get/set. OTOH it does not make sense to set labels without controlling positions, and that's most of the time best done by setting both simultaneously.
Note also that pyplot.xticks() does something siimilar, though it fully merges set_ticks and set_ticklabels`; and I don't think we can mimic this on the Axes due to backward-compatibility (whether that'd be a good idea would need to be evaluated separately..
Reacted by igurin-invn, richard-moss and VongCanhChi
ax.set_xticks(ax.get_xticks()) # just get and reset whatever you already have
ax.set_xticklabels(xtick_labels) # set the new/modified labels
Reacted by Long Hoàng Ngọc, Käthe, Bhaskar-JR, هاجر العرجه, Ben Weisburd, Leroy Pascal, spacewalk01, Florent Roques, Peter M. Stahl, Edy Santoso and 3 more
fwiw I agree with @timhoffm's proposal at #18848 (comment), although a variant (that I think I suggested somewhere else) may be to support ax.set_xticks({pos: label, pos: label, ...}).
In case we should accept a dict, you are free to create that any way you want.
On a side node, note however, that for a dict comprehension {k: v for k, v in zip(positions, labels)}, you'll need to create the k, v pairs anyway using zip(...). dict(zip(...)) is shorter.
Hm can someone summarize the suggested solution after #20047?
Basically I want to do string formatting of the form ax.set_xticklabels([f(t) for t in ax.get_xticklabels()]). I tried using a FuncFormatter, but couldn't get it to work, presumably because I'm using pandas which does something under the hood.
Those are categorical plots; the axis is not the categories, but 0, 1, 2, 3... which is transformed by StrCategoryFormatter into the correct labels. You will probably want to grab the existing formatter, wrap its result, and return that back. Something like:
import matplotlib.ticker as mticker
class SpecialFormatter(mticker.Formatter):
def __init__(self, original_formatter):
self.original_formatter = original_formatter
def __call__(self, x, pos=None):
x = self.original_formatter(x, pos=pos)
return f"{x}, {pos}"
ax.xaxis.set_major_formatter(SpecialFormatter(ax.xaxis.get_major_formatter()))
Thanks, I figured that the category-indexes were transformed by a formatter.
I feel that requires a lot more knowledge of the internals than what I was doing before, and it's quite a common operation.
Basically if you want to apply a function to the ticks in an existing plot, this is what you have to do. Was that the suggested solution before as well?
Basically this is a DerivedFuncFormatter that allows me to apply a function to the existing formatter, so it's a bit more complicated than what @jklymak suggested above. For a library this works as a recipe, for a notebook it's not very convenient.
If you're like me and were simply trying to rotate the axis labels without any other changes, the following answer on stack overflow avoids the warning: https://stackoverflow.com/a/52461208/768439.
I ran into the same issue as @amueller - attempting to use FuncFormatter on tick labels that were internally stored as categories. You have to have deep knowledge of Matplotlib to understand what is going on as the labels appear as strings in the plot but are stored as numeric internally.
FuncFormatter always worked on the tick values, not the label text.
The values for categorical should be the strings, but I can't think of a good way to do implement that given the internal mpl architecture needs it to be numeric.
Activity
jklymak commentedon Oct 30, 2020
That's on purpose. You should also explicitly specify the three ticks to go with the label and then this warning should go away.
OTOH I agree the warning is pretty mysterious if u are just using set_xticklabels.
igurin-invn commentedon Oct 30, 2020
I see. It would be good to fix the message.
Also, If you do set the tick locations, you have to do it first (I revised my code sample to show this). Yes, it's cleaner to set the locations first and then the labels, but I don't think it should be a warning. As long as the locator and labels have both been set by the time the plot is drawn, it should be OK.
jklymak commentedon Oct 30, 2020
The problem is when people zoom or otherwise change the view, and we continue to use an AutoLocator, the labels will often end up applied to the wrong ticks. By encouraging you to manually specify the ticks we help you avoid that possibility.
timhoffm commentedon Oct 31, 2020
Possibly adding a warning a
matplotlib/lib/matplotlib/axis.py
Line 1739 in 5ba3911
makes sense.
Rational-IM commentedon Nov 1, 2020
Thanks, @jklymak: now I understand why the warning was included. However, I'm assuming there is a lot of code out there - the one I use the most on a day-to-day basis included - that only plots "fixed" charts. Therefore, having to add a line of code using FixedLocator (if what I want is just to format the existing labels), would make the conde unnecessarily polluted, no? Maybe the potential issue you describe should be included somewhere on matplotlib's documentation?
jklymak commentedon Nov 1, 2020
Its a warning that you are doing something poorly defined. If you want to suppress it either specify the ticks
filter the Warning, or just ignore it.
timhoffm commentedon Nov 1, 2020
Side note: I'm tempted to modify
set_ticks()from
set_ticks(ticks, *, minor=False)to
set_ticks(ticks, *, labels=None, minor=False).That would allow to
set_ticks([1, 2, 3], labels=['$\pi$', '$2\pi$', '$3\pi$'])and would exactly prevent this problem. A bit hesitant because that'd break the symmetry between get/set. OTOH it does not make sense to set labels without controlling positions, and that's most of the time best done by setting both simultaneously.Note also that
pyplot.xticks()does something siimilar, though it fully mergesset_ticksand set_ticklabels`; and I don't think we can mimic this on the Axes due to backward-compatibility (whether that'd be a good idea would need to be evaluated separately..hrr2020 commentedon Apr 10, 2021
This worked fine in a similar situation:
anntzer commentedon Apr 14, 2021
fwiw I agree with @timhoffm's proposal at #18848 (comment), although a variant (that I think I suggested somewhere else) may be to support
ax.set_xticks({pos: label, pos: label, ...}).jklymak commentedon Apr 14, 2021
I would find a dict hard to remember and assemble. But two matching lists seems fine to me...
timhoffm commentedon Apr 14, 2021
A single parameter would work relatively well also if you start with two lists, either as dict
and/or as list of tuples
My concern is however, that we basically don't have such compound parameters in our API and mostly use separate parameters.
igurin-invn commentedon Apr 15, 2021
I would probably assemble such a dict using a dict comprehension.
timhoffm commentedon Apr 15, 2021
In case we should accept a dict, you are free to create that any way you want.
On a side node, note however, that for a dict comprehension
{k: v for k, v in zip(positions, labels)}, you'll need to create the k, v pairs anyway usingzip(...).dict(zip(...))is shorter.anntzer commentedon Apr 15, 2021
I'm not overly wedded to the dict idea either, but it's likely that the absence of such APIs in our codebase just reflects our matlab heritage.
igurin-invn commentedon Apr 15, 2021
@timhoffm , I disagree.
{tick: f(tick) for tick in positions}would be very convenient.Boo Matlab!
1 remaining item
amueller commentedon May 22, 2021
Hm can someone summarize the suggested solution after #20047?
Basically I want to do string formatting of the form
ax.set_xticklabels([f(t) for t in ax.get_xticklabels()]). I tried using aFuncFormatter, but couldn't get it to work, presumably because I'm using pandas which does something under the hood.Example:
I would have expected
xto bea,bandcbut it's not.What I had before was something like
ugly workaround for
QuLogic commentedon May 22, 2021
Those are categorical plots; the axis is not the categories, but 0, 1, 2, 3... which is transformed by
StrCategoryFormatterinto the correct labels. You will probably want to grab the existing formatter, wrap its result, and return that back. Something like:amueller commentedon May 22, 2021
Thanks, I figured that the category-indexes were transformed by a formatter.
I feel that requires a lot more knowledge of the internals than what I was doing before, and it's quite a common operation.
Basically if you want to apply a function to the ticks in an existing plot, this is what you have to do. Was that the suggested solution before as well?
Basically this is a
DerivedFuncFormatterthat allows me to apply a function to the existing formatter, so it's a bit more complicated than what @jklymak suggested above. For a library this works as a recipe, for a notebook it's not very convenient.jklymak commentedon May 22, 2021
Sorry if I'm not following, what is wrong with the following? It seems to work fine with categoricals?
Olshansk commentedon Aug 20, 2021
If you're like me and were simply trying to rotate the axis labels without any other changes, the following answer on stack overflow avoids the warning: https://stackoverflow.com/a/52461208/768439.
tdpetrou commentedon Dec 7, 2021
I ran into the same issue as @amueller - attempting to use
FuncFormatteron tick labels that were internally stored as categories. You have to have deep knowledge of Matplotlib to understand what is going on as the labels appear as strings in the plot but are stored as numeric internally.The easiest solution seems to be:
jklymak commentedon Dec 7, 2021
That seems orthogonal to this issue, and has always been the case - FuncFormatter always worked on the tick values, not the label text.
story645 commentedon Dec 7, 2021
The values for categorical should be the strings, but I can't think of a good way to do implement that given the internal mpl architecture needs it to be numeric.
fix matplotlib warning. More on this here: matplotlib/matplotlib#18848
Warning rework (#778)
Use matplotlib FuncFormatter to convert ds2 to d-spacings (#1953)
fix matplotlib warning
Fix matplotlib warning