在运行环境没有相应字体并且默认字体是中文的情况下进行的配置:
中文设置代码: import matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=['DengXian']#用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False#用来正常显示负号 2. 系统字体查看 可通过命令fc-list :lang=zh查看当前环境支持的中文字体 3. 其他字体下载 若无当前可用字体则需下载,此处以黑体为例。 3.1 matplotlib目录 在python命令行输入如下语句
import matplotlib print(matplotlib.matplotlib_fname())样例输出:
/home/rh/.pyenv/versions/3.6.10/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc其中matplotlibrc为可编辑文件。 3.2 下载字体到先前输出文件子目录下
目录为:mpl-data/fonts/ttf/3.3 编辑matplotlibrc文件 修改如下代码
font.family : sans-serif font.sans-serif : SimHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serifaxes.unicode_minus,将True改为False,作用就是解决负号’-'显示为方块的问题 其中前两行为去掉#号,第二行在冒号后添加下载的字体(注意拼写、大小写),等线相应拼写为DengXian。
3.4 删除matplotlib缓存
rm -rf /home/rh/.cache/matplotlib可通过如下代码查看缓存位置:
print(matplotlib.get_cachedir())注:换用其他的显示中文代码可能无效。
附缺失字体warning:
findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans. findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans. /home/rh/.pyenv/versions/3.6.10/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py:238: RuntimeWarning: Glyph 20928 missing from current font. font.set_text(s, 0.0, flags=flags) /home/rh/.pyenv/versions/3.6.10/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py:238: RuntimeWarning: Glyph 34701 missing from current font. font.set_text(s, 0.0, flags=flags) /home/rh/.pyenv/versions/3.6.10/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py:238: RuntimeWarning: Glyph 36164 missing from current font. font.set_text(s, 0.0, flags=flags) /home/rh/.pyenv/versions/3.6.10/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py:238: RuntimeWarning: Glyph 39069 missing from current font. font.set_text(s, 0.0, flags=flags) /home/rh/.pyenv/versions/3.6.10/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py:238: RuntimeWarning: Glyph 20159 missing from current font. font.set_text(s, 0.0, flags=flags)