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