Search code examples
pythonpython-2.7matplotlibfont-sizeticker

change fontsize of each tick of one axis with python matplotlib


I am trying to change each tick size for the y-axis.
Theses ticks are words and I would like that the size of theses words increase if the sum of the row is bigger and decrease otherwise. I'm saying row because my graph is representing a matrix.

For example, we could imagine that the sum of the row of the word "windows" would have a higher value than "police". How is it possible to increase the fontsize of the tick "windows" without changing all the others?

I'm using matplotlib 1.3.1 on Python 2.7.6

However I'm ready to use any other toolboxes if needed.


Solution

  • You can loop through the ticks (plt.gca().xaxis.get_major_ticks()) and set properties like this:

    import matplotlib.pyplot as plt
    
    MP_TICKSIZE = [10.0, 15.0, 20.0]
    
    plt.subplot(111)
    
    x = [1.0, 2.0, 3.0]
    y = [1.0, 2.0, 3.0]
    
    plt.plot(x,y)
    
    plt.gca().set_xticks([t for t in x])
    
    count = 0
    for tick in plt.gca().xaxis.get_major_ticks():
        tick.label1.set_fontsize(MP_TICKSIZE[count])
        count += 1
    
    plt.show()  
    

    This will result in this plot:

    enter image description here

    There are two things to note:

    1. You can set the individual tick-label size by looping through the major ticks (this is what the for loop does. If you have a specific axis handle, use it instead of gca().
    2. You need to know the number of ticks for this example (otherwise, your index will be out of bounds sooner or later)

    If you do not want to set your ticks in advance, you can figure out the number of ticks through len(plt.gca().xaxis.get_major_ticks()). Based on that integer you can set up the array MP_TICKSIZE, e.g.:

    import numpy as np
    
    MP_TICKSIZE = np.random.rand(len(plt.gca().xaxis.get_major_ticks())) * 30.0
    

    Use this instead of plt.gca().set_xticks([t for t in x]) to see the difference.