Search code examples
pythonmatplotlibplotcolorsxticks

Every tick label in different color


I'm trying to create a scatter-plot with matplotlib (python 3.5) in which every tick on the x-axes has a different color. How is this possible?

For example let's say the x-ticks are 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'. Now I want 'Mo' to be green, 'Tu' to be blue, ect...

Here is a very simple version of my code:

from matplotlib import pyplot as plt
plt.figure(figsize=(16, 11))
x = [1, 2, 3, 4, 5, 6, 7]
y = [10, 12, 9, 10, 8, 11, 10]
plt.scatter(x, y)
plt.xticks(x, ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'])
plt.show()

I already tried

my_colors = ['c', 'b', 'r', 'r', 'g', 'k', 'b']
plt.xticks(x, ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'], color=my_colors)

but that doesn't work.


Solution

  • You can loop over the tick labels (using plt.gca().get_xticklabels()) and set their colors after they have been created, using .set_color(). For example:

    from matplotlib import pyplot as plt
    plt.figure(figsize=(16, 11))
    x = [1, 2, 3, 4, 5, 6, 7]
    y = [10, 12, 9, 10, 8, 11, 10]
    plt.scatter(x, y)
    plt.xticks(x, ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'])
    
    my_colors = ['c', 'b', 'r', 'r', 'g', 'k', 'b']
    
    for ticklabel, tickcolor in zip(plt.gca().get_xticklabels(), my_colors):
        ticklabel.set_color(tickcolor)
    
    plt.show()
    

    enter image description here