Skip to content

Instantly share code, notes, and snippets.

@andres-fr
Last active March 26, 2023 01:12
Show Gist options
  • Save andres-fr/68d83f79640e31e127d893e6af9e6203 to your computer and use it in GitHub Desktop.
Save andres-fr/68d83f79640e31e127d893e6af9e6203 to your computer and use it in GitHub Desktop.
Setting arbitrary fonts in matplotlib
import matplotlib.pyplot as plt
import matplotlib.font_manager as plt_fm
class PltFontManager:
"""
Sometimes matplotlib finds the system font paths, but setting them can
still be challenging due to using the wrong name or matplotlib complaining
about missing elements.
This manager static class is intended to aid with that, by facilitating
the found paths and their corresponding font names, and providing a
``set_font`` convenience method that will provide the allowed names if
the given one didn't work out.
"""
@staticmethod
def get_font_paths():
"""
:returns: List of paths to the fonts found by matplotlib in the system.
"""
result = plt_fm.findSystemFonts()
return result
@classmethod
def get_font_names(cls):
"""
:returns: A tuple ``(fontnames, errors)``, where ``fontnames`` is a
list with the valid font names that can be used, and ``errors`` is
a dictionary in the form ``font_name: error`` containing fonts that
couldn't be successfully loaded.
"""
fpaths = cls.get_font_paths()
fnames = set()
errors = {}
for fp in fpaths:
try:
fname = plt_fm.FontProperties(fname=fp).get_name()
fnames.add(fname)
except Exception as e:
errors[fp] = e
#
return fnames, errors
@classmethod
def set_font(cls, font_name="Liberation Mono"):
"""
:param font_name: A valid font name as the ones retrieved by the
``get_font_names`` method
This method attempts to set the given font. If that is not possible,
it will inform the user and provide a list of available fonts.
"""
try:
plt_fm.findfont(font_name, fallback_to_default=False)
plt.rcParams["font.family"] = font_name
except ValueError as ve:
print(ve)
print("Available fonts:")
print(sorted(cls.get_font_names()[0]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment