Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color of specific ticks at plot with matplotlib

Using matplotlib, is there an option to change the color of specific tick labels on the axis?

I have a simple plot that show some values by days, and I need to mark some days as 'special' day so I want to mark these with a different color but not all ticks just some specific.

like image 323
Ron Avatar asked Apr 24 '18 09:04

Ron


People also ask

How do I change the tick color in MatPlotLib?

Plot x and y data points using plot() method. To set the color of X-axis tick label in matplotlib, we can use tick_params() method with axis='x' and color='red'. To display the figure, use show() method.

How do you change the color of a tick in Python?

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.) To set the color of axes, i.e., top, left, bottom and right, we can use ax. spines['top'], ax.

How do I specify colors on a MatPlotLib plot?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.

How do I turn on minor ticks in MatPlotLib?

Minor tick labels can be turned on by setting the minor formatter. MultipleLocator places ticks on multiples of some base. StrMethodFormatter uses a format string (e.g., '{x:d}' or '{x:1.2f}' or '{x:1.1f} cm' ) to format the tick labels (the variable in the format string must be 'x' ).


1 Answers

You can get a list of tick labels using ax.get_xticklabels(). This is actually a list of text objects. As a result, you can use set_color() on an element of that list to change the color:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(5,4))
ax.plot([1,2,3])

ax.get_xticklabels()[3].set_color("red")

plt.show()

enter image description here

Alternatively, you can get the current axes using plt.gca(). The below code will give the same result

import matplotlib.pyplot as plt

plt.figure(figsize=(5,4))
plt.plot([1, 2, 3])

plt.gca().get_xticklabels()[3].set_color("red")

plt.show()
like image 173
DavidG Avatar answered Sep 25 '22 12:09

DavidG