0

I've been trying to specify the font for my plots through:

plt.rcParams['font.family'] = ...
plt.rcParams["mathtext.fontset"] = ...

and I've had a lot of headaches because of it. I get the error:

"C:\Users\chris\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\font_manager.py:1241: UserWarning: findfont: Font family ... not found. Falling back to DejaVu Sans."

My goal is the title: Some/Any way really, to specify fonts reliably in mpl. I don't care how many hoops I have to jump through at this point, I just want something to work.

From what I understand, matplotlib.font_manager() finds all the available fonts on my system (no matter where they come from) and provides me with the full path to them. What I tried to do is to generate a sample plot of each font I get from matplotlib.font_manager() and see if I get DejaVuSans of my desired font.

It works for about 12 fonts out of approx. 240. At first I thought that maybe I have the same problem as here: matplotlib does not detect font but I shouldn't have the scoring problem, since I'm getting the fontname from font_manager, right?

There was also a solution on github.com, but I didn't really understand what I was supposed to do with it: https://github.com/matplotlib/matplotlib/issues/13139

Here's my sample code:

import matplotlib.font_manager
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.font_manager import _rebuild; _rebuild()
import re


font_paths = matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf')


fonts = [re.search(r'(?<=Fonts\\)\w+', f_path).group() for f_path in font_paths]


for font in fonts:

    df = pd.DataFrame({'perc': pd.Series([45, 35, 10, 5, 3, 2], index=['A', 'B', 'C','D','E','F'])})

    plt.rcParams['font.family'] = font

    fig, ax = plt.subplots(figsize=(7,4))
    df.iloc[::-1].plot(kind='barh', legend = False, ax=ax)
    ax.set_xlabel('Percentage',fontsize=15)
    ax.set_ylabel('Type',fontsize=15)

    plt.savefig(font+'.png')

Thanks in advance

J.Doe
  • 224
  • 1
  • 4
  • 19
  • Don't take the font path, but the font's name. E.g. I have a font named `"Bernhard BdCn BT"`; its filename is `TT1003M_.TTF`. So surely it cannot be found under the name `TT1003M_`, but rather under `"Bernhard BdCn BT"`. – ImportanceOfBeingErnest Jul 16 '19 at 12:40
  • It is the truncated font name, that's what the re.search(r'(?<=Fonts\\)\w+', f_path).group() is for. You can put it into pythrex to check it. – J.Doe Jul 16 '19 at 14:40
  • Mhh, seems you didn't understand my comment. Sorry for that, someone else might be able to explain it better. – ImportanceOfBeingErnest Jul 16 '19 at 14:46
  • wait...the font name is different from the .ttf file name? What does the rcParams check for then? – J.Doe Jul 16 '19 at 16:56

0 Answers0