1

I would like to write a function that changes the font of all of the labels in a figure that I pass to it without actually changing the labels themselves.

This is useful for figures that I have already created and need to have a uniform font style.

Currently I am using multiple font dictionaries like so:

titleFont = {'family' : 'Arial',
             'weight' : 'bold',
             'size'   : 20}
axesFont = {'family' : 'Arial',
             'weight' : 'bold',
             'size'   : 18}
axesTickFont = {'family' : 'Arial',
                'weight' : 'bold',
                'size'   : 16}`

And then setting the font sizes by using commands along the lines of:

ax.set_title('My Plot',**titleFont)

The issue is that with the command above, I need to specify a plot title, when all I want to do is set the font style of an existing title.

Something like this would be ideal:

def set_fonts(axis):
    axis.set_title(**titleFont)
    axis.set_ylabel(**axesFont)
    axis.set_xlabel(**axesFont)
    return axis

1 Answer 1

1

This is probably not the cleanest solution, but it should do what you want:

def set_fonts(axis):
    axis.set_title(axis.get_title(), **titleFont)
    axis.set_ylabel(axis.get_ylabel(), **axesFont)
    axis.set_xlabel(axis.get_xlabel(), **axesFont)
    return axis

Otherwise you can directly access the relevant artist instances, which avoids reassigning the text:

def set_fonts(axis):
    plt.setp(axis.title, **titleFont)
    plt.setp(axis.xaxis.label, **axesFont)
    plt.setp(axis.yaxis.label, **axesFont)
    return axis
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @hitzg! that works very well. I wasn't able to implement the second solution because I don't know how to point to the ticklabels object. axis.xaxis.ticklabels doesn't work. Do you know where I can find a breakdown of mpl objects so that I can understand better what is going on from an object oriented point of view?
To get the ticklabel objects you can use axis.get_xticklabels() and axis.get_yticklabels(). I agree that it is somewhat inconsistent that some of the getter functions return the artists and some just an attribute of the artist (e.g., axis.get_xlabel() which only returns the text and not the text-artist).
And with the plt.setp method, how could I access the ticklabels?
I guess that plt.setp(axis.get_xticklabels(), **axesFont) should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.