Home > Net >  set xtick label colors based on label string
set xtick label colors based on label string

Time:03-08

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

CodePudding user response:

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

  • Related