Python matplotlib绘图如何显示中文的问题【有报错没有解决】

一文详解matplotlib的配置文件以及配置方式
主要介绍路径问题和配置文件相关介绍
linux安装字体库(simSun为例)可以在终端中显示中文
Matlab绘图中下标、斜体及希腊字母的使用方法

python画图可能会报警告findfont: Font family [‘sans-serif’] not found. Falling back to Bitstream Vera Sans,这时需要在matplotlib库下更新字体信息。
我们可以把win10下的字体复制到matplotlib的文字字体路径/home/warmtree/anaconda3/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf里面:
在这里插入图片描述
扩展一些字体的英文,用时查询

字体 英文
宋体 SimSun
黑体 SimHei
微软雅黑 Microsoft YaHei
微软正黑体 Microsoft JhengHei
新宋体 NSimSun
新细明体 PMingLiU
细明体 MingLiU
标楷体 DFKai-SB
仿宋 FangSong
楷体 KaiTi
隶书 LiSu
幼圆 YouYuan
华文细黑 STXihei
华文楷体 STKaiti
华文宋体 STSong
华文中宋 STZhongsong
华文仿宋 STFangsong
方正舒体 FZShuTi
方正姚体 FZYaoti
华文彩云 STCaiyun
华文琥珀 STHupo
华文隶书 STLiti
华文行楷 STXingkai
华文新魏 STXinwei

Python实现matplotlib显示中文的方法详解
字体配置文件在如下路径:
在这里插入图片描述
遇到报错

/home/warmtree/anaconda3/lib/python3.7/site-packages/matplotlib/mathtext.py:843: MathTextWarning: Font 'default' does not have a glyph for '\u4f4d' [U+4f4d], substituting with a dummy symbol.
  MathTextWarning)
/home/warmtree/anaconda3/lib/python3.7/site-packages/matplotlib/mathtext.py:843: MathTextWarning: Font 'default' does not have a glyph for '\u79fb' [U+79fb], substituting with a dummy symbol.
  MathTextWarning)
/home/warmtree/anaconda3/lib/python3.7/site-packages/matplotlib/mathtext.py:843: MathTextWarning: Font 'default' does not have a glyph for '\u8377' [U+8377], substituting with a dummy symbol.
  MathTextWarning)
/home/warmtree/anaconda3/lib/python3.7/site-packages/matplotlib/mathtext.py:843: MathTextWarning: Font 'default' does not have a glyph for '\u8f7d' [U+8f7d], substituting with a dummy symbol.
  MathTextWarning)

通过查找,我们发现其实错误的是中文的显示。Unicode编码转换
在这里插入图片描述

示例代码

#-*- coding: utf-8 -*-
import matplotlib.pyplot as plt	
# 下述是为保证中文宋体,英文stix(近似Times New Roman),更具体说明见https://zhuanlan.zhihu.com/p/118601703	
# 实际上做的是$$内应用LaTex语法,采用字体为mathtext.fontset=stix,其外默认的字体为宋体SimSun	
import matplotlib as mpl

from matplotlib.font_manager import FontProperties
#font_chinese = FontProperties(fname=r"/media/warmtree/Windows/Windows/Fonts/simsun.ttc", size=24)

''' 
print(matplotlib.get_backend())    #返回matplotlib的后端
print(matplotlib.get_cachedir())   #缓存目录
print(matplotlib.get_configdir())  #配置目录
print(matplotlib.get_data_path())  #数据路径
print(matplotlib.get_home())       #用户目录
'''
mpl.rcParams['font.sans-serif'] = ['SimSun']#显示中文
mpl.rcParams['font.serif'] = ['SimSun']
plt.style.use('classic')	
plt.rcParams['legend.framealpha'] = 0  # 图例框完全透明	
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号	
config1 = {
    
    	
    "font.family": 'sans-serif',	
    "font.size": 24,	
}	
plt.rcParams.update(config1)
config2={
    
    
    'text.usetex': False,
    'mathtext.fontset': 'stix',
}
plt.rcParams.update(config2)
ax = plt.figure().add_subplot(111)
ax.set_ylabel(u'\u8377\u8f7d'+r'$P\rm{/kN}$')
ax.set_xlabel(u'\u4f4d\u79fb'+r'${\it l\Delta}\rm{/mm}$')
plt.show()

猜你喜欢

转载自blog.csdn.net/weixin_44991673/article/details/111730557