Description
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'])
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'])
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)
.