0

I am trying to plot certain values, and I need to display certain xlabels in different color than the rest. I am able to set the color of all labels using "plt.xticks(color = 'r')", but I need certain labels to be in different color than red. Is there any way I can do that? Thanks! :)

1 Answer 1

1

You can get the xlabels with ax.xaxis.get_xticklabels() and then access individual color values with tick.set_color('r').

For example:

fig, ax = plt.subplots()

ax.plot(np.random.randn(100).cumsum(), c='k')

colors = ['r','b']

for n, tl in enumerate(ax.xaxis.get_ticklabels()):
    tl.set_color(colors[n%2])

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Wow, such a quick response. :) Thank you so much, it worked like a charm!!
Okay, it works. but it skips sometimes. I am unable to understand. :( I try the same code on two different datasets and sometimes it changes the color of the labels and sometimes not. Any idea?
Could edit your post with an example replicating the behavior? Maybe you are working with the state-machine interface (plt.plot() etc) and dont have the right axes while working on it. You can get the active axes with ax = plt.gca(). Its guessing without any sample code.
Oh well... yes, I was using plt. to set axis, changing to ax.set_ fixed the issue. Thanks. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.