Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: Every tick 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.

like image 271
Steve Iron Avatar asked Sep 09 '16 10:09

Steve Iron


People also ask

How do I change the tick color in MatPlotLib?

To set the color for X-axis and Y-axis, we can use the set_color() method (Set both the edgecolor and the facecolor). To set the ticks color, use tick_params method for axes. Used arguments are axis ='x' (or y or both) and color = 'red' (or green or yellow or ...etc.)

Can ticks change color?

Ticks are easier to identify once they are done feeding because their body becomes engorged. The scutum remains the same size, but the body will become larger and change color once feeding is complete. The colors range from brownish red to pale gray or greenish grey.


1 Answers

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

like image 130
tmdavison Avatar answered Oct 19 '22 20:10

tmdavison