2

I am looking to change the color of the ticklabels in my heatmap based on some condition. For example below, I would like to change the colors of ticklabels containing A as red and B as green.

I tried making a list ['red', 'green', 'red', 'green'] and pass it along the color option but no success so far. Any help would be great.

import numpy as np
import matplotlib.pyplot as plt

alpha = ['ABC', 'BDF', 'ADF', 'BCF']

data = np.random.random((4,4))

fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(data, interpolation='nearest')
fig.colorbar(cax)

ax.set_xticklabels(['']+alpha)
ax.set_yticklabels(['']+alpha)

plt.show()

enter image description here

1 Answer 1

2

You can set the text colour using set_color on the label text objects:

for l in ax.xaxis.get_ticklabels()+ax.yaxis.get_ticklabels():
    if 'A' in l.get_text():
        l.set_color('r')
    elif 'B' in l.get_text():
        l.set_color('g')

enter image description here

Of course, this doesn't address what happens if both A and B are present in the label (i.e. should ABC be red or green)?

Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect. Thank you so much ... the conditions do not overlap so not a problem at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.