解决Linux系统中python matplotlib画图的中文显示问题
本文解决Linux系统中Python matplotlib画图横坐标中文显示为方框的问题。通过获取matplotlibrc路径、安装中文字体、修改配置文件及清理缓存,实现中文正常显示。
问题背景与原因
在Linux CentOS 7环境下,使用Python 2.7及conda安装的matplotlib和pandas时,常遇到画图横坐标中文显示为方框的现象。这主要因为Linux系统默认缺少中文字体,且matplotlib默认仅支持ASCII码,不支持Unicode编码。
解决步骤
1. 获取matplotlib配置文件路径
首先,在Jupyter Notebook中运行以下代码,获取matplotlibrc文件的具体路径:
import matplotlib
matplotlib.matplotlib_fname()输出示例:u'~/miniconda2/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc'
2. 检查系统可用中文字体
运行以下Python代码,检查系统中可用的中文字体:
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.split('\n'))
available = mat_fonts & zh_fonts
print '*' * 10, '可用的字体', '*' * 10
for f in available:
print f若可用字体列表为空,则说明系统无中文字体。
3. 安装中文字体
下载ttf格式的中文字体文件(如WenQuanYi Zen Hei Mono),并在/usr/share/fonts路径下创建字体文件夹。将下载的ttf文件复制到该文件夹,并改名为英文名以便操作。
在CentOS中安装该字体,执行以下命令:
cd /usr/share/fonts/yourfontsdir
#生成字体索引信息. 会显示字体的font-family
sudo mkfontscale
sudo mkfontdir
#更新字体缓存:
fc-cache4. 修改matplotlib配置文件
打开matplotlibrc文件,去掉font.family部分的注释,并在font.serif支持字体列表中增加中文字体(如WenQuanYi Zen Hei Mono)。同时,去掉中文减号显示方块的注释,将axes.unicode_minus设置为False:
axes.unicode_minus : False5. 清理缓存并验证
将ttf字体文件复制到matplotlib字体缓存目录(如~/miniconda2/lib/python2.7/site-packages/matplotlib/mpl-data/fonts/ttf),并删除字体相关的cache文件(如~/.cache/matplotlib)。重新画图验证中文显示效果。
总结
通过以上步骤,成功解决了Linux系统中Python matplotlib画图中文显示为方框的问题。关键在于获取配置文件路径、安装中文字体、修改配置文件及清理缓存。
以上就是解决Linux系统中python matplotlib画图的中文显示问题的详细内容,更多关于Python Linux matplotlib中文显示的资料请关注本站其它相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













