Original Source: MacOS系统下matplotlib中SimHei中文字体缺失报错的解决办法. However, in this article is in Chinese
. Therefore, I will translate it into English
and add some of my own experience.
When we use matplotlib
to display Chinese characters in Mac OS
, you may encounter the following error due to the lack of Chinese fonts:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
First, we need to enter the Python3
environment in the terminal, and then import the matplotlib
library. Then we can use the following command to find the path of the font file:
import matplotlib
print(matplotlib.matplotlib_fname())
For example, my path is /Users/yubocai/anaconda3/envs/mlp/lib/python3.9/site-packages/matplotlib/mpl-data/matplotlibrc
.
Here you can find the link of Simhei font: Simhei. After downloading, you can find the SimHei.ttf
file in the Simhei
folder.
Copy the SimHei.ttf
file to the path found in Step 1. For example, my path is /Users/yubocai/anaconda3/envs/mlp/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf
. Note that this time is in his ttf
folder.
import matplotlib
print(matplotlib.get_cachedir())
Then you can get /Users/your_compute_name/.matplotlib
. Then exist python environment and delete the file with
rm -rf /Users/your_compute_name/.matplotlib
Open the file matplotlibrc
in the path found in Step 1, and find the following code:
# remove the #
font.family: sans-serif
# remove the #,and add SimHei
font.sans-serif: SimHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
# remove the #,Change True to False
axes.unicode_minus: False # use Unicode for the minus symbol rather than hyphen. See
# https://en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes
Then every thing should be fine. You don't even need the code plt.rcParams['font.sans-serif'] = ['SimHei']
to display Chinese characters.