The SimHei Chinese font in matplotlib under the MacOS system cannot be started
problems encountered
The default font of matplotlib does not have Chinese
So you need to use the following code to call the Chinese font:
plt.rcParams['font.sans-serif'] = ['SimHei']
The following situations may occur during the call:
Solution
1. View the matplotlib font path
Here are two methods:
1. Terminal viewing:
enter the python3 environment in the terminal, and then enter
import matplotlib
print(matplotlib.matplotlib_fname())
Find your own matplotlib font folder path
2. PyCharm or Jupyter
creates a python file (take Jupyter as an example), enter the following code to view the path
import matplotlib
print(matplotlib.matplotlib_fname())
The query results are as follows:
2. Download SimHei font
Here are two download links:
1. Domestic font download website
2. Official website font download
3. Move the downloaded SimHei.ttf to the directory queried in the first step: /Users/dengboyuan/opt/anaconda3/lib/python3.8/site-packages/matplotlib/mpl-data/fonts, pay attention to the name is SimHei.ttf
4. Clean up the matplotlib buffer directory
Open the terminal, enter the python environment, and enter
import matplotlib
print(matplotlib.get_cachedir())
Get the buffer directory address: /Users/dengboyuan/.matplotlib
PyCharm and Jupyter are the same as above.
Enter in the terminal: exit()
Exit the python environment
and rm -rf 路径
delete the buffer file (note the space):
5. Modify the original file
to open the path: /Users/dengboyuan/opt/anaconda3/lib/python3.8/site-packages/matplotlib/mpl-data found The matplotlibrc file is modified as follows:
font.family: sans-serif
#去掉前面的#
font.sans-serif: SimHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
#去掉前面的#,手动添加SimHei
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
#去掉前面的#,把True改为False
6. Restarting Jupyter can automatically display Chinese
without needing it . So far, the problem of Chinese display has been solved.plt.rcParams['font.sans-serif'] = ['SimHei']