matplotlib 中文乱码解决方法

以Win10为例,其他系统步骤基本相同

1. 找到matplotlib 配置文件:

import matplotlib 
print(matplotlib.matplotlib_fname()) 
# 我自己的输出结果如下:
# D:\Program Files\Python37\Lib\site-packages\matplotlib\mpl-data

2. 打开并修改文件 matplotlibrc

        删除 font.family 和 font.sans-serif 两行前的 #,并在 font.sans-serif 后添加中文字体,比如黑体simhei (注意,也可为其他中文字体,但必须为英文字体名,中文字体名无效)

        取消 axes.unicode_minus 前面的 #,且把值改为 false  (作用是解决负号'-'显示为方块的问题)

3. 下载并安装字体: simhei.ttf (非必须步骤)

        一般电脑上都自带黑体,在 C:\Windows\Fonts 中找到 simhei.ttf 或其他想要使用的中文字体后,就不必再额外下载安装字体

# D:\Program Files\Python36\Lib\site-packages\matplotlib\mpl-data\fonts\ttf

4. 删除.matplotlib/cache里面的两个缓存字体文件

C:\Users\你的用户名\.matplotlib

        或者名为:fontList xxx .json

5. 重启Python或Pycharm等编译环境

        大功告成!

补充,执行下这段程序--可以打印出电脑可用的中文字体:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
from matplotlib.font_manager import FontManager
import subprocess

fm = FontManager()
mat_fonts = set(f.name for f in fm.ttflist)
#print(mat_fonts)
output = subprocess.check_output('fc-list :lang=zh -f "%{family}\n"', shell=True)
#print( '*' * 10, '系统可用的中文字体', '*' * 10)
#print (output)
zh_fonts = set(f.split(',', 1)[0] for f in output.decode('utf-8').split('\n'))
available = mat_fonts & zh_fonts
print ('*' * 10, '可用的字体', '*' * 10)
for f in available:
     print (f)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值