Khalil's Blog

Research | ML | Software Engineering

Resetting Matplotlib Font Cache

For convenience and performance reasons, matplotlib uses a font cache to track the fonts installed on your machine. This cache is often stored in plaintext in your home directory but is seldom refreshed unless you explicitly tell matplotlib to do so.

For this reason, matplotlib will raise a non-disruptive warning when you try to use a custom or newly-added font in your plots, e.g.:

UserWarning: findfont: Font family [‘sans-serif’] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext]))

Such a warning tells you that matplotlib is working off an old font cache that does not include the specified font.

To reset matplotlib’s font cache:

  • First, identify the location of the font cache on disk; it is usually the ~/.matplotlib directory. Alternatively, you can programmatically find the cache location by running this command in Terminal:

    python -c 'import matplotlib; print(matplotlib.get_cachedir())
  • In the cache directory, you’ll find a JSON file containing the font list (e.g. fontlist-v330.json).

  • Delete the JSON file to remove the font cache.

  • Finally, run the following in a Python script to rebuild the font cache: python -c ‘from matplotlib.font_manager import FontManager; FontManager().findfont(“xyz”, rebuild_if_missing=True)’

Note that this approach to resetting matplotlib’s cache was tested in v3.5.1 but might differ in older versions.