Using Chinese Characters in Matplotlib
When you try to display Chinese or other non-ascii characters in matplotlib, your characters may not be displayed properly, like following figure:
It is because the fonts used by matplotlib couldn’t decode the characters properly.
To fix it, we should add the appropriate fonts and update matplotlib font cache.
- locate the matplotlib fonts folder:
this is the location of matplotlib config file, you will get something like
The font folder is …/matplotlib/mpl-data/fonts/ttf , put your ttf file there.
- Get ttf from ttc file (skip if you have ttf file already)
For macOS, the system Chinese fonts is Heiti, which is embed in a ttc file (ttc is a collection of multiple ttf files). Get the system ttc file in
/System/Library/Fonts/STHeiti Medium.ttc Copy this file out and convert it to ttf. Here is an online ttc converter:
- Rebuild the Matplotlib Cache
restart your Jupyter / ipython kernel, then test if matplotlib can load your font or not by the
ttflist function of the font manager
change ‘Heiti’ to your own font name. If you see your fonts object above. You are ready to use the new fonts.
- Using Appropriate Fonts in Matplotlib
This will tell matplotlib to use the specific font as default, result as follow~