详解Python Matplot中文显示完美解决方案

yipeiwu_com4年前Python基础

原因与现象

Matplot是一个功能强大的Python图表绘制库,很遗憾目前版本自带的字体库中并不支持中文字体。所以如果在绘制内容中需要显示中文,那么就会显示为方格字符。

解决办法

有一个较为完美的解决方案,通过扫描Matplot自带字体库以及系统字体库,寻找能够支持的中文字体,如果能够找到的话,就设置第一个为Matplot的字体熟悉。

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontManager
from pylab import mpl
import subprocess

def get_matplot_zh_font():
 fm = FontManager()
 mat_fonts = set(f.name for f in fm.ttflist)

 output = subprocess.check_output('fc-list :lang=zh -f "%{family}\n"', shell=True)
 zh_fonts = set(f.split(',', 1)[0] for f in output.split('\n'))
 available = list(mat_fonts & zh_fonts)

 print '*' * 10, '可用的字体', '*' * 10
 for f in available:
 print f
 return available

def set_matplot_zh_font():
 available = get_matplot_zh_font()
 if len(available) > 0:
 mpl.rcParams['font.sans-serif'] = [available[0]] # 指定默认字体
 mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题

在绘图之前,调用set_matplot_zh_font()设置一下就可以了。

效果

如下图所示:

以上所述是小编给大家介绍的Python Matplot中文显示完美解决方案详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

python批量导出导入MySQL用户的方法

数据库迁移(A -> B),需要把用户也迁移过去,而用户表(mysql.user)有上百个用户。有2种方法进行快速迁移:1,在同版本的条件下,直接备份A服务器的mysql数据库,还...

使用grappelli为django admin后台添加模板

grappelli是github上面star最多的django模板系统 http://django-grappelli.readthedocs.org/en/latest/quickst...

Python使用wxPython实现计算器

本文实例为大家分享了wxPython实现计算器的具体代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- ########################...

ubuntu上安装python的实例方法

怎么在ubuntu安装python? python在ubuntu下有几种安装方法: ● 通过ubuntu官方的apt工具包安装 ● 通过PPA(Personal Package Arch...

python中numpy.zeros(np.zeros)的使用方法

翻译: 用法:zeros(shape, dtype=float, order='C') 返回:返回来一个给定形状和类型的用0填充的数组; 参数:shape:形状 dtype:数据类型,可...