【Python】彻底解决图形中:中文字体显示「豆腐块」问题!

机器学习初学者

共 2591字,需浏览 6分钟

 ·

2023-10-16 12:34

本文分享如何彻底解决图形中:中文/韩文/日文等亚洲字体显示「豆腐块」问题!


10W字《Python可视化教程1.0》来了!👇

  • 最近发现一个很nice的Matplotlib字体管理工具-mplfonts,可彻底解决Matplotlib亚洲字体 (中文、韩文及日文等)显示问题轻松管理Matplotlib字体库
  • 本文详细介绍mplfonts使用。

mplfonts安装

pip install mplfonts -i https://pypi.tuna.tsinghua.edu.cn/simple

mplfonts设置

以下两种方法等效,

  • 方法1、在终端设置:

mplfonts init即可。

  • 方法2、在代码中加入
from mplfonts.bin.cli import init
init()

mplfonts解决matplotlib中文显示问题

使用mplfonts前,

import matplotlib.pyplot as plt

plt.style.use('fivethirtyeight')
plt.figure(dpi=120)
plt.plot([123])
plt.title('家人们~,欢迎关注公众号:pythonic生物人', color='red')

令人抓狂的豆腐块,下面尝试mplfonts的效果,

from mplfonts import use_font

use_font('Noto Serif CJK SC')#指定中文字体

plt.style.use('fivethirtyeight')
plt.figure(dpi=120)
plt.plot([123])
plt.title('家人们~,欢迎关注公众号:pythonic生物人', color='red')
plt.show()

豆腐块不见了,中文显示问题完美解决!!!


mplfonts管理matplotlib字体库

如果你认为mplfonts仅仅能解决“中文显示”这么简单的问题,那你就太小瞧它了,mplfonts更大的作用在于管理matploblib的字体库

  • mplfonts安装一种自定义的字体

终端执行,

mplfonts install --update 你的一套字体路径
  • mplfonts安装一批自定义的字体

终端执行,

mplfonts install --update 你的一批字体文件夹路径
  • mplfonts绘图代码中指定字体

以下两行代码即可,

from mplfonts import use_font
use_font('Noto Serif CJK SC'#指定字体

use_font('Noto Serif CJK SC')这里使用了Noto宋体,之所以可以直接调用,是因为在安装mplfonts时,一些开源的字体就已经一起下载了,它们是:

Noto Sans Mono CJK SC:Noto等宽黑体
Noto Serif CJK SC:Noto宋体
Noto Sans CJK SC:Noto黑体
Source Han Serif SC:思源宋体
Source Han Mono SC:思源等宽宋体
  • mplfonts调用系统中任意字体

除了以上5种字体外,你也可以调用系统中任意字体,不知道字体在哪里,终端中使用mplfonts list即可轻松帮你找到,例如,cmb10.ttf字体绝对路径:/Users/xx/anaconda/anaconda3/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/ttf/cmb10.ttf,

from mplfonts import use_font

use_font('/Users/xx/anaconda/anaconda3/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/ttf/cmb10.ttf')#指定cmb10.ttf字体绝对路径

plt.style.use('fivethirtyeight')
plt.figure(dpi=120)
plt.plot([123])
plt.title('家人们~,欢迎关注公众号:pythonic生物人', color='red')
plt.show()

ref: https://github.com/Clarmy/mplfonts

-END-

10W字《Python可视化教程1.0》来了!👇

点个 在看 就是最大的支持

浏览 474
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报