解决Python中Jupyter绘图Matplotlib中文显示问题(适用于Mac和Windows)

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

 

 

物联沃分享整理
物联沃-IOTWORD物联网 » 解决Python中Jupyter绘图Matplotlib中文显示问题(适用于Mac和Windows)

发表回复