在pycharm中利用jupyter开发,发现图片不能正常显示中文;
方法一 独立的指定中英文字体
直接指定字体的类型
from matplotlib.font_manager import FontProperties
chinese_font = FontProperties(family='SimHei')
english_font = FontProperties(family='Times New Roman')
然后在标签的位置设定字体,如果不设定,就会用默认的字体,比如
plt.xlabel(‘位置’, fontproperties=chinese_font, fontsize=14)
完整Python代码
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
plt.rcParams.update({'font.size': 12}) # Setting the global font size to 12
chinese_font = FontProperties(family='SimHei')
english_font = FontProperties(family='Times New Roman')
means = [[1.0, 1.0, 1.0], [0.9, 0.9, 0.9], [0.8, 0.8, 0.8]] # 每个柱子的平均值
stds = [[0.00, 0.00, 0.05], [0.5, 0.8, 0.7], [0.6, 0.9, 0.8]] # 每个柱子的标准差
labels= ["类别1", "类别2", "类别2"]
n_groups = 3 # 组数
n_bars = 3 # 每组的柱子数
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.2
colors = ['#344964', '#ACB2BC', '#B1D8E7', '#475EA4']
for i in range(n_bars):
bars = ax.bar(index + i * bar_width, [means[j][i] for j in range(n_groups)], bar_width, alpha=0.8, color=colors[i], label=labels[i])
for bar in bars:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width() / 2., 1.01*height,
f'{height:.2f}',
ha='center', va='bottom')
plt.title("English Title", fontproperties=english_font, fontsize=16)
plt.xlabel('位置', fontproperties=chinese_font, fontsize=14)
plt.ylabel('准确率',fontproperties=chinese_font, fontsize=14)
plt.ylim([0, 1.1])
plt.xticks(index + bar_width, ['中心', '环上', '边缘'], fontproperties=chinese_font, fontsize=14)
plt.legend()
plt.tight_layout()
# plt.savefig('test.jpg', format='jpg', dpi=900, bbox_inches='tight', pad_inches=0)
# plt.savefig('test.pdf', format='pdf',bbox_inches='tight', pad_inches=0)
plt.show()
这种设置方式不受默认字体的影响,也最为自由,比较推荐
下面推荐两种一劳永逸的办法
方法二 A 一行代码设置统一中文字体
参考 Link 的代码,找到当前系统支持的字体
import matplotlib as mpl
a = sorted([f.name for f in mpl.font_manager.fontManager.ttflist])
for i in a:
print(i)
通过大致的字体名字,能大致推断是不是支持中文字体的,比如:
然后在画图的代码开头加上
plt.rcParams['font.sans-serif'] = ['STSong'] # SimHei
千万不要用 plt.rcParams.update({‘font.family’: ‘Times New Roman’}) 这个指令,后续用中文字体会报错。
不同的博主可能给不同的答案,一定要根据自己系统具体支持的字体类型来选择。
这种方法有可能会报错,那么就要尝试下面的方法
方法二 B 修改配置文件设置默认中文字体
1.首先找到当前项目的python解释器所用的字体库(ttf文件夹),比如我用的是anaconda配置的虚拟环境,在我的电脑上路径为:
E:\big\anaconda3\envs\py39\Lib\site-packages\matplotlib\mpl-data\fonts\ttf
py39是虚拟环境,后面的应该都一样
如下图所示
或者使用如下指令运行,得到对应路径。这里参考了link
import matplotlib
print (matplotlib.matplotlib_fname()) # 将会获得matplotlib配置文件
2.下载所需要的字体文件,并将文件放在ttf这个文件夹中。
可以在微软官网下对应的字体,比如SimHei,不要到乱七八糟的网站下载字体,容易出问题。
官网下载
3.修改matplotlib的配置文件。首先回到mpl-data文件夹下,以文本/记事本/vscode 打开matplotlibrc 这个文件,Ctrl+F 搜索 font.family: 找到对应的这三行,如下图所示,取消这两行的注释,并在 font.sans-serif: 后增加 SimHei
- font.family:
- font.sans-serif: 在这一行后面增加 SimHei
保存文件
4.删除用户的缓存文件,可以通过以下指令得到文件目录(可以跳过这一步,如果执行第5步后还是不能显示中文,则返回执行这一步)
# matplotlib缓存的目录
import matplotlib
print(matplotlib.get_cachedir())
'''
C:\Users\sam\.matplotlib
'''
5.重启jupyter内核,默认显示的就是SimHei字体啦
想要默认显示英文字体怎么办?
再次注释font.sans-serif:
或者,用下面的指令就好了
plt.rcParams['font.sans-serif'] = ['Times New Roman']
总之,需要多方尝试,这三种应该涵盖了大部分的情况。