andrew fay
andrew fay

Reputation: 95

Changing the color of specific xticks in matplotlib

I'm looking for a way to change the color of specific xtick values on my plot. For example, I have all my current xtick labels as black, however I want the xtick values at 7,11,12,14,18,25,26 all to be the color red, while leaving every other xtick label as black.

Is there a possible way to do this?

Upvotes: 1

Views: 519

Answers (1)

James
James

Reputation: 36598

You can pull back the line2d objects that display the ticks, and change their color based on their location. You will need to filter the ticklines to only include the displayed ticks (seems to be indicated by the marker).

ax = plt.gca()
for t, loc in zip(filter(lambda x: x.get_marker()==3, ax.xaxis.get_ticklines()), 
                ax.xaxis.get_ticklocs()):
    if loc in (7,11,12,14,18,25,26):
        print(f'Changing tick line at {loc} to red')
        t.set_color('red')

Upvotes: 2

Related Questions