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()
发现效果很不错,当成模板解决其他问题就好。