Python learning process problem record (2): Matplotlib Chinese display problem

Environment: macOS Monterey 12.2.1, Python3.10.2, Matplotlib 3.5.1

Table of contents

Method 1: Modify the configuration file, global font modification

Exceptions

Method 2: rcParams setting, global font modification

Method 3: fontproperties setting, non-global font modification

Method 4: FontProperties setting, non-global font modification


Method 1: Modify the configuration file, global font modification

Search the Internet for solutions, and solve the problem by copying fonts and modifying three texts in matplotlibrc. In most cases, the code can display Chinese normally.

1. Enter the command in the terminal: python to enter the Python interface and enter the code to obtain the path of the configuration file where the matplotlib package is located. For example, mine is:  /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/mpl-data/matplotlibrc

import matplotlib
matplotlib.matplotlib_fname()     #输出matplotlib包所在的配置文件的路径
insert image description here
Get the path to the matplotlib package configuration file

2. Open the folder according to the path obtained in the first step. For example, my path is: /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf

3. Download Chinese fonts from the Internet, such as SimHei.ttf (黑体), SimSun.ttf (宋体), YaHei.ttf (Microsoft Yahei). To ttf format , and install the font .

4. Open the matplotlibrc file with a text editor or sublime Text software . (Location: /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/mpl-data/matplotlibrc )
(1) Find font.family: sans-serif and remove the front # .
(2) Find font.sans-serif: , remove the # in front , and add the SimHei, SimSun, and Microsoft YaHei just now.

insert image description here
Modify the font settings of the matplotlibrc file


(3) Find axes.unicode_minus: True , remove the leading # , and change True to False .

insert image description here
Modify the axes settings of the matplotlibrc file

4. Save and close the matplotlibrc file.

5. Open the /Users/username/.matplotlib folder and delete the files inside. I only have a fontlist-v330.json in it .

6. Most of the codes in the future can display Chinese normally without any settings.

The Chinese title of the graphic drawn by the following code is displayed normally.

import matplotlib.pyplot as plt

input_values = [1, 2, 3, 4, 5, 6]
squares = [1, 4, 9, 16, 25, 36]
fig, ax = plt.subplots()
ax.plot(input_values, squares, linewidth=3)
ax.set_title("平方值", fontsize=20)
ax.set_xlabel("值", fontsize=14)
ax.set_ylabel("平方-值", fontsize=14)
ax.tick_params(axis='both', labelsize=14)
plt.show()
Chinese normal display

Exceptions

Although method 1 modifies the global font settings by modifying the configuration file, the images drawn in the following scenes still cannot display Chinese normally: when the graphics in the code are set with plt.style.use('seaborn') .

It can be solved by method two.

import matplotlib.pyplot as plt
...
plt.style.use('seaborn')    # 上述代码加入此句代码
fig, ax = plt.subplots()
...    
Chinese cannot be displayed normally

Method 2: rcParams setting, global font modification

1. Add the font setting code after plt.style.use('seaborn')  to display Chinese. The font setting code must be behind the seaborn code to take effect.

2. The font setting is only valid for the code following the plt.style.use('seaborn')  of the py file . If the following image uses a statement similar to plt.style.use('seaborn')  , the font code needs to be set again.

import matplotlib.pyplot as plt # 最前面如果已经import,此句可以不要       
...
plt.style.use('seaborn')
# 字体设置代码
plt.rcParams['font.sans-serif'] = 'Microsoft Yahei' # 显示汉字:SimHei黑体,simsum宋体,Microsoft YaHei雅黑。根据系统安装的字体,有的能用有的不能用,我的是这三个可以。
plt.rcParams['axes.unicode_minus'] = False # 正常显示负号
Chinese can be displayed normally again

Method 3: fontproperties setting, non- global font modification

1. In the plt.title(), plt.xlabel(), plt.ylabel() parameter settings, use fontproperties to specify the font.

2. Different fonts can be specified, but the fonts must be in ttf and installed.

import matplotlib.pyplot as plt

input_values = [1, 2, 3, 4, 5, 6]
squares = [1, 4, 9, 16, 25, 36]
plt.style.use('seaborn')
plt.plot(input_values, squares, linewidth=3)
plt.figure("Hello测试中文!",facecolor='lightgray')
plt.title("测试中文",fontsize=20,fontproperties="Microsoft Yahei")
plt.xlabel("X值", fontsize=14,fontproperties="SimHei")
plt.ylabel("Y值", fontsize=14,fontproperties="SimHei")
plt.show()
Chinese is displayed normally (different fonts can be used)

Method 4: FontProperties setting, non- global font modification

This method needs to import the FontProperties module, set the myfont variable, and specify the fontproperties parameter in three steps. Although it is cumbersome, you can specify the font file in ttc format .

1. Import the FontProperties module: from matplotlib.font_manager import FontProperties

2. 设置变量myfont = FontProperties(fname=r"/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/PingFang.ttc", size=14) 

3.  In the parameter setting of  plt.title(), plt.xlabel(), plt.ylabel() , use fontproperties to specify the font as the variable myfont.

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties    # 步骤一

input_values = [1, 2, 3, 4, 5, 6]
squares = [1, 4, 9, 16, 25, 36]
# 步骤二
myfont = FontProperties(fname=r"/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/PingFang.ttc", size=14)

plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(input_values, squares, linewidth=3)
ax.set_title("平方值", fontproperties=myfont)      # 步骤三
ax.set_xlabel("值", fontproperties=myfont)        # 步骤三
ax.set_ylabel("平方-值", fontproperties=myfont)    # 步骤三
ax.tick_params(axis='both', labelsize=14)

plt.show()
Chinese normally displays the specified font

There is also a global font modification method set by rc, which is somewhat similar to method two. But I tried it and it didn't work well, so I didn't write it.

Guess you like

Origin blog.csdn.net/yearx3/article/details/123320809