Search code examples
pythonmatplotlibfonts

Use matplotlib.pyplot.rcparams with a custom font which is not installed


I'm trying to use a custom ttf font not installed in the system for text element in the matplotlib figure.

with plt.style.context('mplparams.mplstyle'):
    plt.plot(np.sin(np.linspace(0, 3 * np.pi)), '-o')

I know I can change the text properties with FontManager but I'm looking for a solution which only involves an external config file.

At the moment I only know that i can change font.sans-serif to a font name, not font path.

Is this possible?


Solution

  • The font to be used has to be known to the Fontmanager, otherwise you cannot get it into the plot. In order to specify a font through rcParams this font must be found in a folder matplotlib would look for it. In case you don't want to install anything, you may copy the .ttf file to the matplotlib font folder. In my case this is

    python\Lib\site-packages\matplotlib\mpl-data\fonts
    

    Then you need to clear the font.chache. Find out its path via print(matplotlib.get_cachedir()) and delete the fontList files. (Or make a backup first if you like).

    Then run your script which has the rcParam specified

    font.sans-serif : <name of font>
    

    or use

    plt.rcParams['font.sans-serif'] = "<name of font>"
    

    Also see this question.