I have a series of X-axis axis labels that I put on a plot using:
plt.figure(1)
ax = plt.subplot(111)
ax.bar(Xs, Ys, color="grey",width=1)
ax.set_xticks([i+.5 for i in range(0,count)])
ax.set_xticklabels(Xlabs, rotation=270)
Now I want to color each individual label based on what the label is. For example: I want to apply the rule "color the label red if 1 or blue if 0", something like this:
colors = ['blue','red']
ax.set_xticklabels(Xlabs, rotation=270, color = [colors[i] for i in Xlabs])
But that is not valid. Is there any way I can achieve this?
You can do this by iterating over your x-tick labels and setting their color to the color you want.
Here's an example of doing this, using your code snippet.
import numpy as np
import matplotlib.pyplot as plt
count = 3
Xs = np.arange(3)
Ys = np.random.random(3)
Xlabs = ('Blue', 'Red', 'Green')
plt.figure(1)
ax = plt.subplot(111)
ax.bar(Xs, Ys, color="grey", width=1)
ax.set_xticks([i + .5 for i in range(0, count)])
ax.set_xticklabels(Xlabs, rotation=270)
colors = ['b', 'r', 'g']
for xtick, color in zip(ax.get_xticklabels(), colors):
xtick.set_color(color)
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With