【补档】CentOS7 下解决 Python3 使用 Matplotlib 生成图表时中文乱码的问题
本文最后更新于 751 天前,其中的信息可能已经有所发展或是发生改变。

不需要 Yum 安装任何其他软件,也不需要修改 Matplotlib 包的配置文件,实测是最简单的方法了。
全程使用 HostVDS 新开的服务器并只安装了 Python3.8.2 以保证教程正确。


1、首先看下没有安装字体时生成含中文的图表时会出现上面错误。

import sys
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

"""
@description: 执行 SQL 
-------
@param:
-------
@return:
"""
def main():
    # 一般教程都会用到的所谓指定字体路径,此篇教程用不到
    # font_prop = FontProperties(fname="/usr/local/python3/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/ttf/SimHei.ttf")
    # 待字体安装完后指定字体,SimHei 存在缺少部分特殊符号的问题,所以用 YaHei
    # mpl.rcParams['font.sans-serif'] = ["Microsoft YaHei"]
    # 防止 - 号出错,和上一行同时解注
    # mpl.rcParams["axes.unicode_minus"] = False
    data = [["AAA", "BBB", "CCC", "数据", "数据"]]
    column_labels = ["商品中文名", "商品英文名", "最低售价", "在售数量", "更新时间"]
    fig = plt.figure(figsize=(3, 3), dpi=600)
    ax = fig.add_subplot(111, frame_on=False,)
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    ax.table(cellText=data, colLabels=column_labels)
    ax.set_title("测试")
    plt.savefig('test.png')

"""
@description: 单体测试
-------
@param:
-------
@return:
"""
if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(str(e))

直接运行后日志和图片如下所示:

[root@test test]# python3 main.py
/usr/local/python3/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py:240: RuntimeWarning: Glyph 27979 missing from current font.
  font.set_text(s, 0.0, flags=flags)
/usr/local/python3/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py:240: RuntimeWarning: Glyph 35797 missing from current font.
  font.set_text(s, 0.0, flags=flags)
/usr/local/python3/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py:240: RuntimeWarning: Glyph 25968 missing from current font.
  font.set_text(s, 0.0, flags=flags)
/usr/local/python3/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py:240: RuntimeWarning: Glyph 25454 missing from current font.
  font.set_text(s, 0.0, flags=flags)

无指定中文

2、给系统安装中文字体。
这里不考虑一般教程所采用的只给 Matplotlib 安装中文字体。

# 新建中文文件夹并下载微软雅黑字体
cd /usr/share/fonts/
mkdir chinese
chmod -R 755 chinese
cd chinese
wget https://www.wfonts.com/download/data/2014/06/01/microsoft-yahei/chinese.msyh.ttf
# 查看当前系统里的中文字体以确认安装成功
fc-list :lang=zh

出现以下命令则说明安装成功:

[root@test chinese]# fc-list :lang=zh
/usr/share/fonts/chinese/chinese.msyh.ttf: Microsoft YaHei:style=Regular,Normal

清除之前 Matplotlib 的缓存后此步骤结束。

[root@test chinese]# rm ~/.cache/matplotlib -R
rm: descend into directory ‘/root/.cache/matplotlib’? y
rm: remove regular file ‘/root/.cache/matplotlib/fontlist-v330.json’? y
rm: remove directory ‘/root/.cache/matplotlib’? y

3、再执行图片生成脚本以确认中文字体安装成功。
解注以下两行:

        ...
        # 待字体安装完后指定字体,SimHei 存在缺少部分特殊符号的问题,所以用 YaHei
        mpl.rcParams['font.sans-serif'] = ["Microsoft YaHei"]
        # 防止 - 号出错,和上一行同时解注
        mpl.rcParams["axes.unicode_minus"] = False
        ...

无乱码

成功,结束。

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇