Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Keep explicit ticklabels in sync with ticks from FixedLocator #17266

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
May 11, 2020
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions doc/api/api_changes_3.3/behaviour.rst
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ did nothing, when passed an unsupported value. It now raises a ``ValueError``.
`.pyplot.tick_params`) used to accept any value for ``which`` and silently
did nothing, when passed an unsupported value. It now raises a ``ValueError``.

``Axis.set_ticklabels()`` must match ``FixedLocator.locs``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If an axis is using a `.ticker.FixedLocator`, typically set by a call to
`.Axis.set_ticks`, then the number of ticklabels supplied must match the
number of locations available (``FixedFormattor.locs``). If not, a
``ValueError`` is raised.

``backend_pgf.LatexManager.latex``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``backend_pgf.LatexManager.latex`` is now created with ``encoding="utf-8"``, so
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ def annotate_heatmap(im, data=None, valfmt="{x:.2f}",
# the diagonal elements (which are all 1) by using a
# `matplotlib.ticker.FuncFormatter`.

corr_matrix = np.corrcoef(np.random.rand(6, 5))
corr_matrix = np.corrcoef(harvest)
im, _ = heatmap(corr_matrix, vegetables, vegetables, ax=ax4,
cmap="PuOr", vmin=-1, vmax=1,
cbarlabel="correlation coeff.")
Expand Down
1 change: 1 addition & 0 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3016,6 +3016,7 @@ def locator_params(self, axis='both', tight=None, **kwargs):
self.yaxis.get_major_locator().set_params(**kwargs)
self._request_autoscale_view(tight=tight,
scalex=update_x, scaley=update_y)
self.stale = True

def tick_params(self, axis='both', **kwargs):
"""
Expand Down
36 changes: 31 additions & 5 deletions lib/matplotlib/axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""

import datetime
import functools
import logging

import numpy as np
Expand Down Expand Up @@ -1599,6 +1600,11 @@ def set_pickradius(self, pickradius):
"""
self.pickradius = pickradius

# Helper for set_ticklabels. Defining it here makes it pickleable.
@staticmethod
def _format_with_dict(tickd, x, pos):
return tickd.get(x, "")

def set_ticklabels(self, ticklabels, *, minor=False, **kwargs):
r"""
Set the text values of the tick labels.
Expand Down Expand Up @@ -1626,14 +1632,34 @@ def set_ticklabels(self, ticklabels, *, minor=False, **kwargs):
"""
ticklabels = [t.get_text() if hasattr(t, 'get_text') else t
for t in ticklabels]
locator = (self.get_minor_locator() if minor
else self.get_major_locator())
if isinstance(locator, mticker.FixedLocator):
if len(locator.locs) != len(ticklabels):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

L 1620 probably needs something like "Number of labels must be the same as number of ticks set by set_ticks or the FixedLocator"?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a reference to set_ticks.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That helps, but I mean above in the Parameter description. Its a bit unclear as to what is meant by "tick labels". maybe:

ticklabels : sequence of str or of `.Text`\s
            List of texts for tick labels, one for each tick defined in `.axis.set_ticks`.

raise ValueError(
"The number of FixedLocator locations"
f" ({len(locator.locs)}), usually from a call to"
" set_ticks, does not match"
f" the number of ticklabels ({len(ticklabels)}).")
tickd = {loc: lab for loc, lab in zip(locator.locs, ticklabels)}
func = functools.partial(self._format_with_dict, tickd)
formatter = mticker.FuncFormatter(func)
else:
formatter = mticker.FixedFormatter(ticklabels)

if minor:
self.set_minor_formatter(mticker.FixedFormatter(ticklabels))
ticks = self.get_minor_ticks()
self.set_minor_formatter(formatter)
locs = self.get_minorticklocs()
ticks = self.get_minor_ticks(len(locs))
else:
self.set_major_formatter(mticker.FixedFormatter(ticklabels))
ticks = self.get_major_ticks()
self.set_major_formatter(formatter)
locs = self.get_majorticklocs()
ticks = self.get_major_ticks(len(locs))

ret = []
for tick_label, tick in zip(ticklabels, ticks):
for pos, (loc, tick) in enumerate(zip(locs, ticks)):
tick.update_position(loc)
tick_label = formatter(loc, pos)
# deal with label1
tick.label1.set_text(tick_label)
tick.label1.update(kwargs)
Expand Down
24 changes: 22 additions & 2 deletions lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -4441,8 +4441,8 @@ def test_set_get_ticklabels():
# set ticklabel to 1 plot in normal way
ax[0].set_xticks(range(10))
ax[0].set_yticks(range(10))
ax[0].set_xticklabels(['a', 'b', 'c', 'd'])
ax[0].set_yticklabels(['11', '12', '13', '14'])
ax[0].set_xticklabels(['a', 'b', 'c', 'd'] + 6 * [''])
ax[0].set_yticklabels(['11', '12', '13', '14'] + 6 * [''])

# set ticklabel to the other plot, expect the 2 plots have same label
# setting pass get_ticklabels return value as ticklabels argument
Expand All @@ -4452,6 +4452,26 @@ def test_set_get_ticklabels():
ax[1].set_yticklabels(ax[0].get_yticklabels())


def test_subsampled_ticklabels():
# test issue 11937
fig, ax = plt.subplots()
ax.plot(np.arange(10))
ax.xaxis.set_ticks(np.arange(10) + 0.1)
ax.locator_params(nbins=5)
ax.xaxis.set_ticklabels([c for c in "bcdefghijk"])
Comment on lines +4459 to +4461
Copy link
Member

@QuLogic QuLogic May 4, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Putting these together would make it a bit clearer:

Suggested change
ax.xaxis.set_ticks(np.arange(10) + 0.1)
ax.locator_params(nbins=5)
ax.xaxis.set_ticklabels([c for c in "bcdefghijk"])
ax.xaxis.set(ticks=np.arange(10) + 0.1),
ticklabels=[c for c in "bcdefghijk"])
ax.locator_params(nbins=5)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The use of set here would work only by accident, because the kwargs are sorted in inverse order, so that set_ticks will be called before set_ticklabels. I will stick with the individual function calls.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the closest analogue to plt.xticks(locs, labels), so if you're saying it might be broken, then I think that's not good. Especially given the recent tweet about .set()...

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't use twitter and haven't seen the tweet.

I'm not saying the behavior is currently broken, just that it works in this case (I think--I haven't tried it) because the names are sorted in inverse order, and the "s" in "ticks" makes it sort before the first "l" in "ticklabels". It's an accident. It might be better to make it explicit by adding a "ticks" entry to Artist._prop_order to boost its priority. The _prop_order dict provides a way of setting priority at a higher level than the alphanumeric sort. Presently, it serves only to give 'color' low priority, so it is executed last.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The is the tweet that @story645 mentioned.

For users, working by accident and working by design are the same thing. So I meant if this PR breaks it, that would not be good. However, it doesn't, so we're fine, even if it's working by accident right now.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess I'll take advantage of this to point to #16328 :)

plt.draw()
labels = [t.get_text() for t in ax.xaxis.get_ticklabels()]
assert labels == ['b', 'd', 'f', 'h', 'j']


def test_mismatched_ticklabels():
fig, ax = plt.subplots()
ax.plot(np.arange(10))
ax.xaxis.set_ticks([1.5, 2.5])
with pytest.raises(ValueError):
ax.xaxis.set_ticklabels(['a', 'b', 'c'])


@image_comparison(['retain_tick_visibility.png'])
def test_retain_tick_visibility():
fig, ax = plt.subplots()
Expand Down
8 changes: 8 additions & 0 deletions lib/matplotlib/ticker.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,8 +381,10 @@ class FuncFormatter(Formatter):
position ``pos``), and return a string containing the corresponding
tick label.
"""

def __init__(self, func):
self.func = func
self.offset_string = ""

def __call__(self, x, pos=None):
"""
Expand All @@ -392,6 +394,12 @@ def __call__(self, x, pos=None):
"""
return self.func(x, pos)

def get_offset(self):
return self.offset_string

def set_offset_string(self, ofs):
self.offset_string = ofs


class FormatStrFormatter(Formatter):
"""
Expand Down