Matplotlib different colors for each axis label

I have a series of X axis axis labels that I overlay on a graph 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 this is not true. Is there any way to achieve this?

+6
source share
1 answer

You can do this by iterating over your x-tick tags and setting their color to the color you want.

Here is an example of this using a 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

+10
source

Source: https://habr.com/ru/post/971882/


All Articles