Search code examples
pythonpython-3.xmatplotlibplotlabel

Concise way to set axis label font size in matplotlib


I am looking for the most concise way to set axis labels and their font size.

I am aware I can do this:

ax.set_xlabel('X axis', fontsize = 12)
ax.set_ylabel('Y axis', fontsize = 12)

I also know I can use this command to set the labels instead:

ax.set(xlabel = 'X axis', ylabel = 'Yaxis')

However, if I try:

ax.set(xlabel = 'X axis', ylabel = 'Yaxis', fontsize = 12)

I get this error:

TypeError: There is no AxesSubplot property "fontsize"

Can I denote the fontsize within the set method? I'd like to tidy up my code a bit and be as concise as possible.


Solution

  • You could change the label for each "axis" instance of the "axes". The text instance returned by "get_label" provides methods to modify the fonts size, but also other properties of the label:

    from matplotlib import pylab as plt
    import numpy
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.grid()
    
    # set labels and font size
    ax.set_xlabel('X axis', fontsize = 12)
    ax.set_ylabel('Y axis', fontsize = 12)
    
    ax.plot(numpy.random.random(100))
    
    # change font size for x axis
    ax.xaxis.get_label().set_fontsize(20)
    
    plt.show()