Mac OS和Ubuntu1804 Matplotlib和seaborn中文异常

820 阅读1分钟

matplotlib 与 seaborn 中出现中文乱码的解决方法,主要原因是没有适配的中文字体

  1. 下载SimHei字体

    下载链接

  2. 找到你的字体存放路径

在Python环境下

import matplotlib
matplotlib.get_data_path()

得到路径

/usr/local/anaconda3/lib/python3.7/site-packages/matplotlib/mpl-data
  1. 拷贝字体到该路径下的/fonts/ttf文件夹下

  2. 修改matplotlibrc配置文件

vim matplotlibrc

修改以下内容

font.family : sans-serif
font.sans-serif : SimHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
  1. 删除用户目录下的~/.cache/matplotlib文件夹
rm -rf ~/.cache/matplotlib
rm -rf ~/.matplotlib
  1. 重启Jupyter
plt.rcParams['font.family'] = ['SimHei'] #用来正常显示中文标签
sns.set_style({'font.sans-serif':['SimHei']})

常用config

pd.set_option('display.max_columns', None) # df最大列数
pd.set_option('display.max_rows', 40) # df最大行数
pd.set_option('display.float_format', lambda x: '%.3f' % x) # df取消科学计数
plt.rcParams['font.family'] = ['SimHei'] # plt正常显示中文
plt.rcParams['axes.unicode_minus'] = False  # plt正常显示负号
sns.set_style({'font.sans-serif':['SimHei']}) # seaborn正常显示中文