美文网首页
python中matplotlib画图中文乱码的解决方法

python中matplotlib画图中文乱码的解决方法

作者: zh_harry | 来源:发表于2020-03-07 12:51 被阅读0次

问题

在python中使用matplotlib画图,里面的中文会显示乱码方块。

这是由于matplotlib默认使用的字体中不包含中文字符引起的,可以通过将中文字符加入到默认字体中解决。

前提

查找本地都有哪些中文字体
打开matplotlib字体,默认为~/.matplotlib,打开fontlist-${version}.json,查找中文字体如simHei,song,kai等,分别对应简体黑、宋体、楷体等。

 {
      "fname": "/Library/Fonts/\u534e\u6587\u4eff\u5b8b.ttf",
      "name": "STFangsong",
      "style": "normal",
      "variant": "normal",
      "weight": 400,
      "stretch": "normal",
      "size": "scalable",
      "__class__": "FontEntry"
    }

解决方案

运行下面的代码:

import matplotlib
print(matplotlib.matplotlib_fname())

会输出配置文件路径,如:

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc

打开此文件,找到#font.family:和#font.sans-serif:开头的这两行,将两行的注释#去掉,并在font.sans-serif:后添加自己想加入的中文字体名,如:STFangsong

font.family  : sans-serif
#font.style   : normal
#font.variant : normal
#font.weight  : normal
#font.stretch : normal
#font.size    : 10.0

#font.serif      : DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
font.sans-serif :STFangsong, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
#font.cursive    : Apple Chancery, Textile, Zapf Chancery, Sand, Script MT, Felipa, cursive
#font.fantasy    : Comic Neue, Comic Sans MS, Chicago, Charcoal, ImpactWestern, Humor Sans, xkcd, fantasy
#font.monospace  : DejaVu Sans Mono, Bitstream Vera Sans Mono, Computer Modern Typewriter, Andale Mono, Nimbus Mono L, Courier New, Courier, Fixed, Terminal, monospace

运行结果

image.png

相关文章

网友评论

      本文标题:python中matplotlib画图中文乱码的解决方法

      本文链接:https://www.haomeiwen.com/subject/kdoqdhtx.html