How to Display Chinese Character in matplotlib

Beverly Wang
3 min readJan 2, 2022
Photo by Cherry Lin on Unsplash

I met this issue (Chinese characters, or other non-ascii characters) recently when developing an App. It is not complicated to solve, but rewarding to elaborate the solution here considering my bad memory.

  • Download the font file
  • Install the font
  • Display the figure

Download Font File

You can download the font file .ttf online, but the most safe and direct way is to find the font file that is already available in your operation system (Most fonts are available in OS).

In Windows, the font file is usually located at \WINDOWS\SYSTEM or \WINDOWS\FONTS. In MacOS, the font file is located at /System/Library/Fonts/. Heiti (STHeiti Medium.ttc) is the default Chinese font file in MacOS. However, it is in .ttc format and need to be converted to .ttf. The online converter is available at: https://transfonter.org/ttc-unpack

After find and convert the file to the proper format, copy this file to a specific folder. You can copy it to a project folder (e.g. Desktop/Testproject/font) or to matplotlib font folder. To find matplotlib font folder, run the command to get location of matplotlib config file

import matplotlib
print(matplotlib.matplotlib_fname())

The result looks like …/matplotlib/mpl-data/matplotlibrc.The font folder is …/matplotlib/mpl-data/fonts/ttf.

Install Font File

Somehow, the following rebuilt command does not work for me as I kept meeting the issue below.

import matplotlib.font_manager
matplotlib.font_manager._rebuild()

But when I check if the font file has been installed properly by:

[f for f in matplotlib.font_manager.fontManager.ttflist if ‘Heiti’ in f.name]

It actually shows that Heiti font file has been installed properly. Given that, I can set the below properties before all the figure I plan to display.

matplotlib.rcParams[‘font.family’] = [‘Heiti TC’]

Method 2: There is another way to work around, too.

Manually specify the font file location and set font properties and then specify font property in each figure element.

import matplotlib.font_manager as fm
font_path = ‘Desktop/Testproject/font/STHeitiTC-Medium.ttf’
my_font = fm.FontProperties(fname=font_path)

Display the Figure

Method 1:

The figure will be:

Method 2:

This method will generate exactly the same figure as above.

Reference

https://blog.birost.com/a?ID=8d64d25d-66c5-4745-9f11-9ee7dfc8bf48

--

--