0

I have a plot with a list of labels. What I'd like to do is color code each label based on the string. So, for instance, all labels with the string ':Q_D' would refer to quadrupoles and should get a certain color. The other substrings to color by are ':DCH_D' and ':DCV_D' for horizontal and vertical corrector magnets.

I see that you can change the color of all xtick labels using this: plt.xticks(color='r') but I'd like to have them individually colored. Is this possible?

plot with xtick labels

Daniel Crisp
  • 107
  • 11
  • Does this answer your question? [Formatting only selected tick labels](https://stackoverflow.com/questions/41924963/formatting-only-selected-tick-labels) – Mr. T Mar 07 '22 at 22:35
  • It's close, but not quite. It describes how to change a given xtick label, but specifically states that they don't know how to tell which one your changing other than trial and error. "The problem is that it's not intuitively clear which of the elements would be the one we are looking for" – Daniel Crisp Mar 08 '22 at 01:57

1 Answers1

1

You could loop through the tick labels, check whether they contain the given string, and set the color:

from matplotlib import pyplot as plt
import numpy as np
from random import choice, randint

# first create some test data
labels = [f"REA_BTS{randint(25, 35)}:{choice(['DCV_D', 'DCH_D', 'Q_D'])}{randint(1100, 1500)}:I_CSET"
          for _ in range(20)]

# create the plot
fig, ax = plt.subplots(figsize=(12, 6))
for _ in range(7):
    ax.plot(labels, np.random.randn(20).cumsum())
ax.tick_params(axis='x', labelrotation=90)
ax.margins(x=0.01)  # less whitespace inside the plot left and right
plt.tight_layout()

# set the colors of the tick labels; note that the tick labels are 
# only filled in after plt.tight_layout() or after a draw
for t in ax.get_xticklabels():
    txt = t.get_text()
    print(t.get_text())
    if 'Q_D' in txt:
        t.set_color('tomato')
    elif 'DCV_D' in txt:
        t.set_color('cornflowerblue')
    elif 'DCH_D' in txt:
        t.set_color('lime')
plt.show()

changing individual tick label colors

JohanC
  • 71,591
  • 8
  • 33
  • 66
  • thanks you so much for taking the time to answer this one! I really appreciate it! lol, I love the names of your color choices too. This works perfectly and makes so much sense. Thank you, thank you, thank you. – Daniel Crisp Mar 08 '22 at 02:02