1

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?

shadesofdarkred
  • 313
  • 3
  • 15

1 Answers1

3

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.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • So I guess it's not possible to use a path to ttf file directly in rcParams without copying it into either system font or mpl font directory? – shadesofdarkred Dec 12 '17 at 15:42
  • It's definitely not possible to use the path in rcParams. What might still be possible somehow (but I wouldn't know how) would be to specify the fontname in rcParams after getting the font to load into the Fontmanager from a path that is outside the default search path for fonts or to manipulate the search path as to include some custom path. – ImportanceOfBeingErnest Dec 12 '17 at 15:51
  • I see.. Well since this is the next best thing, I gonna accept this answer. Thanks! – shadesofdarkred Dec 13 '17 at 10:17