Skip to content

[Bug]: ax.set_xticklables doesn't work proper together with ax.set_xticklabels #23158

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

Closed
Tian-Jionglu opened this issue May 29, 2022 · 1 comment

Comments

@Tian-Jionglu
Copy link

Tian-Jionglu commented May 29, 2022

Bug summary

It was supposed to rotate the xticklabes with clauses:

xticks = ax.get_xticks()
xticklabes = ax.get_ticklabels()
ax.set_xticks(xticks)
ax.set_xticklabels(xticklabels, rotation=90)

But it got empty xticklables as a result.

Code for reproduction

Snippet 1:

import matplotlib.pyplot as plt
import numpy as np

y = np.arange(10)
ax = plt.subplot()
ax.plot(y)
xticks = ax.get_xticks()
xticklabels = ax.get_xticklabels()
ax.set_xticks(xticks)

Snippet 2:

import matplotlib.pyplot as plt
import numpy as np

y = np.arange(10)
ax = plt.subplot()
ax.plot(y)
xticks = ax.get_xticks()
xticklabels = ax.get_xticklabels()
ax.set_xticks(xticks)
ax.set_xticklabels(xticklabes, rotation=90)

Actual outcome

As the result of Snippet 1, variable xticklabels got correct result of current plot.
But when it came to Snippet 2, xticklabels became empty []. And plot show no xticklabes.

Expected outcome

outcome of snippet 1:
snippet_1

outcome of snippet 2:
snippet_2

Additional information

No response

Operating system

Windows 10

Matplotlib Version

3.5.2

Matplotlib Backend

No response

Python version

3.8.10

Jupyter version

3.0.6

Installation

pip

@timhoffm
Copy link
Member

The tick labels are initially empty texts and only formatted and written out at draw time, when we know the final size of the axes. You would have to insert a manual draw before getting the labels. Note however, that this approach is not well suited if you only want to change the style of the ticks.

When you set the labels as above you technically change to a fixed locator and formatter (If you are not familiar with these concepts: think you have a set of fixed labels at fixed positions). The ticks labels will not adapt anymore e.g. if you zoom or pan.

What you actually want is tick_params()

import matplotlib.pyplot as plt
import numpy as np

y = np.arange(10)
ax = plt.subplot()
ax.plot(y)
ax.tick_params('x', rotation=90)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants