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

别说谁变了你拦得住时间么 提交于 2019-12-25 01:48:46

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/47757755/use-matplotlib-pyplot-rcparams-with-a-custom-font-which-is-not-installed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!