Matplotlib: coloring axis/tick labels

34,943

Solution 1

  label = plt.ylabel("y-label")
  label.set_color("red")

similarly, you can obtain and modify the tick labels:

[i.set_color("red") for i in plt.gca().get_xticklabels()]

Solution 2

The xlabel can be colorized when setting it,

ax.set_xlabel("x-label", color="red")

For setting the ticklabels' color, one may either use tick_params, which sets the ticklabels' as well as the ticks' color

ax.tick_params(axis='x', colors='red')

enter image description here

Alternatively, plt.setp can be used to only set the ticklabels' color, without changing the ticks' color.

plt.setp(ax.get_xticklabels(), color="red")

enter image description here

Note that for changing the properties on the y-axis, one can replace the x with a y in the above.

Share:
34,943
dimka
Author by

dimka

Updated on June 04, 2020

Comments

  • dimka
    dimka about 4 years

    How would one color y-axis label and tick labels in red?

    So for example the "y-label" and values 0 through 40, to be colored in red. sample_image

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.arange(10)
    
    fig = plt.figure()
    ax = plt.subplot(111)
    ax.set_ylabel("y-label")
    
    for i in xrange(5):
        ax.plot(x, i * x, label='$y = %ix$' % i)
    
    ax.legend()
    
    plt.show()
    
  • eric
    eric about 3 years
    I wonder why for tick_params it uses the keyword colors and not color like the others? (Just spent 10 minutes debugging this because I used the wrong word)
  • Tobias P. G.
    Tobias P. G. about 2 years
    I would generally suggest a for loop in the second case, since assigning and returning values in a list comprehension is considered bad practice.
  • markling
    markling almost 2 years
    Documentation of tick_params here: matplotlib.org/3.1.1/api/_as_gen/… (though seems incomplete ... font weight?)