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
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])

4 Comments
C.M
Wow, such a quick response. :) Thank you so much, it worked like a charm!!
C.M
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?
Rutger Kassies
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.C.M
Oh well... yes, I was using plt. to set axis, changing to ax.set_ fixed the issue. Thanks. :)