Plotting fonts when using matplotlib

Posted by Bruce Liu on January 14, 2020

🏷️ Tags: python , matplotlib , font

How to set different font when plotting with matplotlib in python?

  • Set locally, for example set font for title:
      tfont = {'fontname':'Times New Roman'}
      plt.title('title',**tfont)
    
  • Set globally:
      import matplotlib.pyplot as plt
      plt.rcParams['font.family'] = 'Times New Roman'
    

    If it works fine, that’s ok. If it return something like the following:

      findfont: Font family ['.....'] not found. Falling back to DejaVu Sans.
    

    Then continue.

Check first:

  • Precautiously check matplotlib font cache or let it go:
      cd ~/.cache/matplotlib && ls
    

    There may have a json file as the matplotlib font cache file. Check if the expected font exists.

    • If the font exists, this is NOT for you and you can STOP here.
    • If not, continue.
  • Check if the expected font exists in the system:
      fc-list : family | sort
    

    or

      fc-list -f '%{file}\n' | sort
    

    or

      fc-list : lang=zh
    

    or

      fc-list :lang=zh -f "%{family}\n" | sort | uniq
    

    If needed, install fontconfig first.

    • If the font exists, go here.
    • If not, go here.

How to install a font in Linux

  • Require preferred font. NOTICE truetype format (.ttc/.ttf)
  • Copy it to the fonts directory
      cp <font path> /usr/share/fonts/<somewhere>
    

Update the font cache in Linux

  • re-generate font cache:
      sudo fc-cache -fv
    

    If needed, install fontconfig first.

Remove current matplotlib font cache

  • Precautiously backup first:
      cp -r ~/.cache/matplotlib <somewhere>
    
  • Remove it:
      rm -fr ~/.cache/matplotlib
    

Re-run the plotting script

Normally, the matplotlib font cache will re-generate automatically. That’s it.


Reference:


Share on:

« PREVIOUS: How to Enable Copy and Paste Keyboard Shortcuts in WSL
NEXT: General concepts of matplotlib »