Python利用Matplotlib绘图无法显示中文字体的解决方案 - 路饭网

报错:

/Applications/anaconda3/lib/python3.9/site-packages/IPython/core/pylabtools.py:151: UserWarning: Glyph 33457 (\N{CJK UNIFIED IDEOGRAPH-82B1}) missing from current font.

Mac OS的字体设置和Win不一样,按照一般的流程下载SimHei再放到对应目录没有用。

首先在Jupyter中输入以下命令查看matplotlib中的字体列表:

#查询一下matplotlib中拥有哪些语言
from matplotlib.font_manager import FontManager
mpl_fonts = set(f.name for f in FontManager().ttflist)
print('all font list get from matplotlib.font_manager:')
for f in sorted(mpl_fonts):
    print('\t' + f)
    
#Heiti TC
#Songti SC

经过筛选发现Mac中matplotlib包含Heiti TC和Songti SC两种中文字体。

输入以下命令设置字体,测试效果:

import matplotlib.pyplot as plt
import matplotlib
matplotlib.rc("font", family='Heiti TC')
 
squares = [1, 4, 9, 16, 25]
fig, ax = plt.subplots()
ax.plot(squares, linewidth=3)
#设置图表标题并给坐标轴加上标签。
ax.set_title("主题", size=14)
ax.set_xlabel("横坐标", size=14) # color='red'
ax.set_ylabel("纵坐标", size=14) # color='red'
 
ax.tick_params(axis='both', labelsize=14)
plt.show()

 发现效果很不错,当成模板解决其他问题就好。

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐