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.
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.
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.
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.
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' ).
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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With