Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib different colors for each axis label [duplicate]

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?

like image 715
Tommy Avatar asked Jul 07 '14 18:07

Tommy


1 Answers

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()

Result

like image 66
tbekolay Avatar answered Oct 17 '22 14:10

tbekolay