Python: Custom global fonts for Matplotlib without installation

To use custom TTF font on our own, there are similar posts up on the forums. However, none of them works for my case except this one.

Here's the highlight:


  • Dynamically add custom font to current Python script outside of default system font folder, especially on Linux
  • No big changes to the rest of Python source about adding fontsproperties *kwargs to each text/label statement


Here's example:

        # Set global font style
        mpl = matplotlib
        fm = matplotlib.font_manager
        basedir = os.path.join(os.path.dirname(__file__), 'static', 'fonts')
        fpath = os.path.join(basedir,'times.ttf')
        prop = fm.FontProperties(fname=fpath)

        font_files = fm.findSystemFonts(fontpaths=basedir)
        font_list = fm.createFontList(font_files)
        fm.fontManager.ttflist.extend(font_list)

        logging.debug('Register font family: %s' % (prop.get_name()))
        mpl.rcParams['font.family'] = prop.get_name()
        mpl.rcParams.update({'font.size': '10'})
        
        plt.switch_backend('agg')

This code snippet assigns the basedir with current Python script's location as reference and sub-folder structure like:

[current_folder]/static/fonts/

The best of this is to create custom font list and extend it to current font manager's TTF List. It means it will apply the custom font to existing font family within current Python script as a whole. No more hassle to things to any other statements and it works like the default font.

This example uses Times New Roman TTF font. You can use whatever TTF font you like.





No comments:

Post a Comment

apt install through corporate proxy

Assuming proxy service like CNTLM is up and running on Ubuntu machine, one can use apt-get to install package with specifying http proxy inf...