22

Using matplotlib, is there an option to change the color of specific tick labels on the axis?

I have a simple plot that show some values by days, and I need to mark some days as 'special' day so I want to mark these with a different color but not all ticks just some specific.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Ron
  • 511
  • 1
  • 5
  • 14
  • 1
    This question is a duplicate of [Formatting only selected tick labels](https://stackoverflow.com/questions/41924963/formatting-only-selected-tick-labels) – Trenton McKinney May 24 '20 at 00:42

1 Answers1

41

You can get a list of tick labels using ax.get_xticklabels(). This is actually a list of text objects. As a result, you can use set_color() on an element of that list to change the color:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(5,4))
ax.plot([1,2,3])

ax.get_xticklabels()[3].set_color("red")

plt.show()

enter image description here

Alternatively, you can get the current axes using plt.gca(). The below code will give the same result

import matplotlib.pyplot as plt

plt.figure(figsize=(5,4))
plt.plot([1, 2, 3])

plt.gca().get_xticklabels()[3].set_color("red")

plt.show()
DavidG
  • 24,279
  • 14
  • 89
  • 82
  • 3
    What if I also want to change the color of the small tick above the number 0.50? – gota Apr 14 '20 at 17:04
  • this will do the trick xTicks = plt.xticks(np.arange(3)) ; xTicks[0][2]._apply_params(color='r') ; plt.show() – AlexWach May 23 '23 at 13:35