Skip to content

Semantics of set_xticks for categoricals #12993

Closed

Description

@timhoffm

Following up on a discussion in #12990. I was quite surprised by the semantics of plt.xticks with categoricals.

plt.bar(['a', 'b'], [1 , 2])
plt.xticks(['b', 'c'])

image

Expected behavior

As far as I understand, categoricals are essentially text labels at integer positions on the axis. From
the docstring

Get or set the current tick locations and labels of the x-axis.

I would have expected that the positions are implicit implicit and plt.xticks(['b', 'c']) would set new labels on the existing data. That's apparently not the case.

Actual behavior

Instead, plt.xticks(['b', 'c']) means: show only the category labels given in the argument (and add new categories if they don't exist.

Disambiuation set_xticks vs. set_xticklabels.

On the Axes level, this becomes more clear. The difference between expected and actual behavior is set_xticks vs. set_xticklabels:

fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.bar(['a', 'b'], [1 , 2])
ax2.bar(['a', 'b'], [1 , 2])
ax1.set_xticks(['b', 'c'])
ax2.set_xticklabels(['b', 'c'])

image

Question / Proposal

Is the behavior of plt.xticks intentional? If not, I'd rather change it to call set_xticklabels for categoricals. Either way, the behavior should be documented.

Note also, that in the current implementation, you cannot (easily) do the equivalent of set_xticklabels in pyplot: plt.xticks(labels=...) is not allowed without the positions. You would have to do plt.xticks(range(len(labels)), labels).

Activity

  1. added this to the v3.1 milestone on Dec 15, 2018
  2. jklymak commented on Dec 15, 2018

    @jklymak
    Member

    I’d not use bar as your paradigm when thinking about this. Use scatter or plot and then it will be more clear that set_xticks is just setting the tick values for the axes not the label of the bars. Certainly if I plot 1-4 and set xticks 2, 4, 6, 8 you don’t expect the data to be remapped to 2, 4, 6, 8

  3. changed the title [-]Sematics of set_xticks for categoricals[/-] [+]Semantics of set_xticks for categoricals[/+] on Dec 16, 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

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions