jupyter使用matplotlib进行画图会面临中文无法显示的问题,导致这样的原因是没有配置对应的中文字体,所以无法在画图时显示中文。
Windows版本解决方法
在Window中,采用以下代码
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
Mac版本解决方法
Mac中没有SimHei字体,所以Windows的代码无法使用,所以要先查询mac中支持的中文字体。以下代码可以查询mac中的所有字体。
# 查询当前系统所有字体
from matplotlib.font_manager import FontManager
import subprocess
mac_fonts = set(f.name for f in FontManager().ttflist)
print('all font list get from matplotlib.font_manager:')
for f in sorted(mac_fonts):
print('\t' + f)

以上都是mac系统上的字体,选择一种中文字体就可以显示。例如:

红色标记的就是黑体,将字体写入,代码如下:
import matplotlib
# 解决中文乱码
matplotlib.rcParams['font.sans-serif'] = ['Heiti TC']
matplotlib.rcParams['font.serif'] = ['Heiti TC']
matplotlib.rcParams['axes.unicode_minus'] = False

在Jupyter中使用matplotlib画图时,如果出现中文无法显示的情况,通常是由于缺少中文字体配置。对于Windows系统,可以通过设置`font.sans-serif`为`SimHei`来解决;而对于Mac系统,由于没有SimHei字体,需要查询Mac支持的中文字体,如`HeitiTC`,然后进行相应配置。配置完成后,中文和负号都能正常显示。
1469





